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.

981 lines
41 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*! \file json.hpp
  2. \brief JSON 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_JSON_HPP_
  28. #define CEREAL_ARCHIVES_JSON_HPP_
  29. #include "cereal/cereal.hpp"
  30. #include "cereal/details/util.hpp"
  31. namespace cereal
  32. {
  33. //! An exception thrown when rapidjson fails an internal assertion
  34. /*! @ingroup Utility */
  35. struct RapidJSONException : Exception
  36. { RapidJSONException( const char * what_ ) : Exception( what_ ) {} };
  37. }
  38. // Override rapidjson assertions to throw exceptions by default
  39. #ifndef CEREAL_RAPIDJSON_ASSERT
  40. #define CEREAL_RAPIDJSON_ASSERT(x) if(!(x)){ \
  41. throw ::cereal::RapidJSONException("rapidjson internal assertion failure: " #x); }
  42. #endif // RAPIDJSON_ASSERT
  43. // Enable support for parsing of nan, inf, -inf
  44. #define CEREAL_RAPIDJSON_WRITE_DEFAULT_FLAGS kWriteNanAndInfFlag
  45. #define CEREAL_RAPIDJSON_PARSE_DEFAULT_FLAGS kParseFullPrecisionFlag | kParseNanAndInfFlag
  46. #include "cereal/external/rapidjson/prettywriter.h"
  47. #include "cereal/external/rapidjson/ostreamwrapper.h"
  48. #include "cereal/external/rapidjson/istreamwrapper.h"
  49. #include "cereal/external/rapidjson/document.h"
  50. #include "cereal/external/base64.hpp"
  51. #include <limits>
  52. #include <sstream>
  53. #include <stack>
  54. #include <vector>
  55. #include <string>
  56. namespace cereal
  57. {
  58. // ######################################################################
  59. //! An output archive designed to save data to JSON
  60. /*! This archive uses RapidJSON to build serialize data to JSON.
  61. JSON archives provides a human readable output but at decreased
  62. performance (both in time and space) compared to binary archives.
  63. JSON archives are only guaranteed to finish flushing their contents
  64. upon destruction and should thus be used in an RAII fashion.
  65. JSON benefits greatly from name-value pairs, which if present, will
  66. name the nodes in the output. If these are not present, each level
  67. of the output will be given an automatically generated delimited name.
  68. The precision of the output archive controls the number of decimals output
  69. for floating point numbers and should be sufficiently large (i.e. at least 20)
  70. if there is a desire to have binary equality between the numbers output and
  71. those read in. In general you should expect a loss of precision when going
  72. from floating point to text and back.
  73. JSON archives do not output the size information for any dynamically sized structure
  74. and instead infer it from the number of children for a node. This means that data
  75. can be hand edited for dynamic sized structures and will still be readable. This
  76. is accomplished through the cereal::SizeTag object, which will cause the archive
  77. to output the data as a JSON array (e.g. marked by [] instead of {}), which indicates
  78. that the container is variable sized and may be edited.
  79. \ingroup Archives */
  80. class JSONOutputArchive : public OutputArchive<JSONOutputArchive>, public traits::TextArchive
  81. {
  82. enum class NodeType { StartObject, InObject, StartArray, InArray };
  83. using WriteStream = CEREAL_RAPIDJSON_NAMESPACE::OStreamWrapper;
  84. using JSONWriter = CEREAL_RAPIDJSON_NAMESPACE::PrettyWriter<WriteStream>;
  85. public:
  86. /*! @name Common Functionality
  87. Common use cases for directly interacting with an JSONOutputArchive */
  88. //! @{
  89. //! A class containing various advanced options for the JSON 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( JSONWriter::kDefaultMaxDecimalPlaces, IndentChar::space, 0 ); }
  97. //! The character to use for indenting
  98. enum class IndentChar : char
  99. {
  100. space = ' ',
  101. tab = '\t',
  102. newline = '\n',
  103. carriage_return = '\r'
  104. };
  105. //! Specify specific options for the JSONOutputArchive
  106. /*! @param precision The precision used for floating point numbers
  107. @param indentChar The type of character to indent with
  108. @param indentLength The number of indentChar to use for indentation
  109. (0 corresponds to no indentation) */
  110. explicit Options( int precision = JSONWriter::kDefaultMaxDecimalPlaces,
  111. IndentChar indentChar = IndentChar::space,
  112. unsigned int indentLength = 4 ) :
  113. itsPrecision( precision ),
  114. itsIndentChar( static_cast<char>(indentChar) ),
  115. itsIndentLength( indentLength ) { }
  116. private:
  117. friend class JSONOutputArchive;
  118. int itsPrecision;
  119. char itsIndentChar;
  120. unsigned int itsIndentLength;
  121. };
  122. //! Construct, outputting to the provided stream
  123. /*! @param stream The stream to output to.
  124. @param options The JSON specific options to use. See the Options struct
  125. for the values of default parameters */
  126. JSONOutputArchive(std::ostream & stream, Options const & options = Options::Default() ) :
  127. OutputArchive<JSONOutputArchive>(this),
  128. itsWriteStream(stream),
  129. itsWriter(itsWriteStream),
  130. itsNextName(nullptr)
  131. {
  132. itsWriter.SetMaxDecimalPlaces( options.itsPrecision );
  133. itsWriter.SetIndent( options.itsIndentChar, options.itsIndentLength );
  134. itsNameCounter.push(0);
  135. itsNodeStack.push(NodeType::StartObject);
  136. }
  137. //! Destructor, flushes the JSON
  138. ~JSONOutputArchive() CEREAL_NOEXCEPT
  139. {
  140. if (itsNodeStack.top() == NodeType::InObject)
  141. itsWriter.EndObject();
  142. else if (itsNodeStack.top() == NodeType::InArray)
  143. itsWriter.EndArray();
  144. }
  145. //! Saves some binary data, encoded as a base64 string, with an optional name
  146. /*! This will create a new node, optionally named, and insert a value that consists of
  147. the data encoded as a base64 string */
  148. void saveBinaryValue( const void * data, size_t size, const char * name = nullptr )
  149. {
  150. setNextName( name );
  151. writeName();
  152. auto base64string = base64::encode( reinterpret_cast<const unsigned char *>( data ), size );
  153. saveValue( base64string );
  154. };
  155. //! @}
  156. /*! @name Internal Functionality
  157. Functionality designed for use by those requiring control over the inner mechanisms of
  158. the JSONOutputArchive */
  159. //! @{
  160. //! Starts a new node in the JSON output
  161. /*! The node can optionally be given a name by calling setNextName prior
  162. to creating the node
  163. Nodes only need to be started for types that are themselves objects or arrays */
  164. void startNode()
  165. {
  166. writeName();
  167. itsNodeStack.push(NodeType::StartObject);
  168. itsNameCounter.push(0);
  169. }
  170. //! Designates the most recently added node as finished
  171. void finishNode()
  172. {
  173. // if we ended up serializing an empty object or array, writeName
  174. // will never have been called - so start and then immediately end
  175. // the object/array.
  176. //
  177. // We'll also end any object/arrays we happen to be in
  178. switch(itsNodeStack.top())
  179. {
  180. case NodeType::StartArray:
  181. itsWriter.StartArray();
  182. case NodeType::InArray:
  183. itsWriter.EndArray();
  184. break;
  185. case NodeType::StartObject:
  186. itsWriter.StartObject();
  187. case NodeType::InObject:
  188. itsWriter.EndObject();
  189. break;
  190. }
  191. itsNodeStack.pop();
  192. itsNameCounter.pop();
  193. }
  194. //! Sets the name for the next node created with startNode
  195. void setNextName( const char * name )
  196. {
  197. itsNextName = name;
  198. }
  199. //! Saves a bool to the current node
  200. void saveValue(bool b) { itsWriter.Bool(b); }
  201. //! Saves an int to the current node
  202. void saveValue(int i) { itsWriter.Int(i); }
  203. //! Saves a uint to the current node
  204. void saveValue(unsigned u) { itsWriter.Uint(u); }
  205. //! Saves an int64 to the current node
  206. void saveValue(int64_t i64) { itsWriter.Int64(i64); }
  207. //! Saves a uint64 to the current node
  208. void saveValue(uint64_t u64) { itsWriter.Uint64(u64); }
  209. //! Saves a double to the current node
  210. void saveValue(double d) { itsWriter.Double(d); }
  211. //! Saves a string to the current node
  212. void saveValue(std::string const & s) { itsWriter.String(s.c_str(), static_cast<CEREAL_RAPIDJSON_NAMESPACE::SizeType>( s.size() )); }
  213. //! Saves a const char * to the current node
  214. void saveValue(char const * s) { itsWriter.String(s); }
  215. //! Saves a nullptr to the current node
  216. void saveValue(std::nullptr_t) { itsWriter.Null(); }
  217. private:
  218. // Some compilers/OS have difficulty disambiguating the above for various flavors of longs, so we provide
  219. // special overloads to handle these cases.
  220. //! 32 bit signed long saving to current node
  221. template <class T, traits::EnableIf<sizeof(T) == sizeof(std::int32_t),
  222. std::is_signed<T>::value> = traits::sfinae> inline
  223. void saveLong(T l){ saveValue( static_cast<std::int32_t>( l ) ); }
  224. //! non 32 bit signed long saving to current node
  225. template <class T, traits::EnableIf<sizeof(T) != sizeof(std::int32_t),
  226. std::is_signed<T>::value> = traits::sfinae> inline
  227. void saveLong(T l){ saveValue( static_cast<std::int64_t>( l ) ); }
  228. //! 32 bit unsigned long saving to current node
  229. template <class T, traits::EnableIf<sizeof(T) == sizeof(std::int32_t),
  230. std::is_unsigned<T>::value> = traits::sfinae> inline
  231. void saveLong(T lu){ saveValue( static_cast<std::uint32_t>( lu ) ); }
  232. //! non 32 bit unsigned long saving to current node
  233. template <class T, traits::EnableIf<sizeof(T) != sizeof(std::int32_t),
  234. std::is_unsigned<T>::value> = traits::sfinae> inline
  235. void saveLong(T lu){ saveValue( static_cast<std::uint64_t>( lu ) ); }
  236. public:
  237. #ifdef _MSC_VER
  238. //! MSVC only long overload to current node
  239. void saveValue( unsigned long lu ){ saveLong( lu ); };
  240. #else // _MSC_VER
  241. //! Serialize a long if it would not be caught otherwise
  242. template <class T, traits::EnableIf<std::is_same<T, long>::value,
  243. !std::is_same<T, std::int32_t>::value,
  244. !std::is_same<T, std::int64_t>::value> = traits::sfinae> inline
  245. void saveValue( T t ){ saveLong( t ); }
  246. //! Serialize an unsigned long if it would not be caught otherwise
  247. template <class T, traits::EnableIf<std::is_same<T, unsigned long>::value,
  248. !std::is_same<T, std::uint32_t>::value,
  249. !std::is_same<T, std::uint64_t>::value> = traits::sfinae> inline
  250. void saveValue( T t ){ saveLong( t ); }
  251. #endif // _MSC_VER
  252. //! Save exotic arithmetic as strings to current node
  253. /*! Handles long long (if distinct from other types), unsigned long (if distinct), and long double */
  254. template <class T, traits::EnableIf<std::is_arithmetic<T>::value,
  255. !std::is_same<T, long>::value,
  256. !std::is_same<T, unsigned long>::value,
  257. !std::is_same<T, std::int64_t>::value,
  258. !std::is_same<T, std::uint64_t>::value,
  259. (sizeof(T) >= sizeof(long double) || sizeof(T) >= sizeof(long long))> = traits::sfinae> inline
  260. void saveValue(T const & t)
  261. {
  262. std::stringstream ss; ss.precision( std::numeric_limits<long double>::max_digits10 );
  263. ss << t;
  264. saveValue( ss.str() );
  265. }
  266. //! Write the name of the upcoming node and prepare object/array state
  267. /*! Since writeName is called for every value that is output, regardless of
  268. whether it has a name or not, it is the place where we will do a deferred
  269. check of our node state and decide whether we are in an array or an object.
  270. The general workflow of saving to the JSON archive is:
  271. 1. (optional) Set the name for the next node to be created, usually done by an NVP
  272. 2. Start the node
  273. 3. (if there is data to save) Write the name of the node (this function)
  274. 4. (if there is data to save) Save the data (with saveValue)
  275. 5. Finish the node
  276. */
  277. void writeName()
  278. {
  279. NodeType const & nodeType = itsNodeStack.top();
  280. // Start up either an object or an array, depending on state
  281. if(nodeType == NodeType::StartArray)
  282. {
  283. itsWriter.StartArray();
  284. itsNodeStack.top() = NodeType::InArray;
  285. }
  286. else if(nodeType == NodeType::StartObject)
  287. {
  288. itsNodeStack.top() = NodeType::InObject;
  289. itsWriter.StartObject();
  290. }
  291. // Array types do not output names
  292. if(nodeType == NodeType::InArray) return;
  293. if(itsNextName == nullptr)
  294. {
  295. std::string name = "value" + std::to_string( itsNameCounter.top()++ ) + "\0";
  296. saveValue(name);
  297. }
  298. else
  299. {
  300. saveValue(itsNextName);
  301. itsNextName = nullptr;
  302. }
  303. }
  304. //! Designates that the current node should be output as an array, not an object
  305. void makeArray()
  306. {
  307. itsNodeStack.top() = NodeType::StartArray;
  308. }
  309. //! @}
  310. private:
  311. WriteStream itsWriteStream; //!< Rapidjson write stream
  312. JSONWriter itsWriter; //!< Rapidjson writer
  313. char const * itsNextName; //!< The next name
  314. std::stack<uint32_t> itsNameCounter; //!< Counter for creating unique names for unnamed nodes
  315. std::stack<NodeType> itsNodeStack;
  316. }; // JSONOutputArchive
  317. // ######################################################################
  318. //! An input archive designed to load data from JSON
  319. /*! This archive uses RapidJSON to read in a JSON archive.
  320. As with the output JSON archive, the preferred way to use this archive is in
  321. an RAII fashion, ensuring its destruction after all data has been read.
  322. Input JSON should have been produced by the JSONOutputArchive. Data can
  323. only be added to dynamically sized containers (marked by JSON arrays) -
  324. the input archive will determine their size by looking at the number of child nodes.
  325. Only JSON originating from a JSONOutputArchive is officially supported, but data
  326. from other sources may work if properly formatted.
  327. The JSONInputArchive does not require that nodes are loaded in the same
  328. order they were saved by JSONOutputArchive. Using name value pairs (NVPs),
  329. it is possible to load in an out of order fashion or otherwise skip/select
  330. specific nodes to load.
  331. The default behavior of the input archive is to read sequentially starting
  332. with the first node and exploring its children. When a given NVP does
  333. not match the read in name for a node, the archive will search for that
  334. node at the current level and load it if it exists. After loading an out of
  335. order node, the archive will then proceed back to loading sequentially from
  336. its new position.
  337. Consider this simple example where loading of some data is skipped:
  338. @code{cpp}
  339. // imagine the input file has someData(1-9) saved in order at the top level node
  340. ar( someData1, someData2, someData3 ); // XML loads in the order it sees in the file
  341. ar( cereal::make_nvp( "hello", someData6 ) ); // NVP given does not
  342. // match expected NVP name, so we search
  343. // for the given NVP and load that value
  344. ar( someData7, someData8, someData9 ); // with no NVP given, loading resumes at its
  345. // current location, proceeding sequentially
  346. @endcode
  347. \ingroup Archives */
  348. class JSONInputArchive : public InputArchive<JSONInputArchive>, public traits::TextArchive
  349. {
  350. private:
  351. using ReadStream = CEREAL_RAPIDJSON_NAMESPACE::IStreamWrapper;
  352. typedef CEREAL_RAPIDJSON_NAMESPACE::GenericValue<CEREAL_RAPIDJSON_NAMESPACE::UTF8<>> JSONValue;
  353. typedef JSONValue::ConstMemberIterator MemberIterator;
  354. typedef JSONValue::ConstValueIterator ValueIterator;
  355. typedef CEREAL_RAPIDJSON_NAMESPACE::Document::GenericValue GenericValue;
  356. public:
  357. /*! @name Common Functionality
  358. Common use cases for directly interacting with an JSONInputArchive */
  359. //! @{
  360. //! Construct, reading from the provided stream
  361. /*! @param stream The stream to read from */
  362. JSONInputArchive(std::istream & stream) :
  363. InputArchive<JSONInputArchive>(this),
  364. itsNextName( nullptr ),
  365. itsReadStream(stream)
  366. {
  367. itsDocument.ParseStream<>(itsReadStream);
  368. if (itsDocument.IsArray())
  369. itsIteratorStack.emplace_back(itsDocument.Begin(), itsDocument.End());
  370. else
  371. itsIteratorStack.emplace_back(itsDocument.MemberBegin(), itsDocument.MemberEnd());
  372. }
  373. ~JSONInputArchive() CEREAL_NOEXCEPT = default;
  374. //! Loads some binary data, encoded as a base64 string
  375. /*! This will automatically start and finish a node to load the data, and can be called directly by
  376. users.
  377. Note that this follows the same ordering rules specified in the class description in regards
  378. to loading in/out of order */
  379. void loadBinaryValue( void * data, size_t size, const char * name = nullptr )
  380. {
  381. itsNextName = name;
  382. std::string encoded;
  383. loadValue( encoded );
  384. auto decoded = base64::decode( encoded );
  385. if( size != decoded.size() )
  386. throw Exception("Decoded binary data size does not match specified size");
  387. std::memcpy( data, decoded.data(), decoded.size() );
  388. itsNextName = nullptr;
  389. };
  390. private:
  391. //! @}
  392. /*! @name Internal Functionality
  393. Functionality designed for use by those requiring control over the inner mechanisms of
  394. the JSONInputArchive */
  395. //! @{
  396. //! An internal iterator that handles both array and object types
  397. /*! This class is a variant and holds both types of iterators that
  398. rapidJSON supports - one for arrays and one for objects. */
  399. class Iterator
  400. {
  401. public:
  402. Iterator() : itsIndex( 0 ), itsType(Null_) {}
  403. Iterator(MemberIterator begin, MemberIterator end) :
  404. itsMemberItBegin(begin), itsMemberItEnd(end), itsIndex(0), itsType(Member)
  405. {
  406. if( std::distance( begin, end ) == 0 )
  407. itsType = Null_;
  408. }
  409. Iterator(ValueIterator begin, ValueIterator end) :
  410. itsValueItBegin(begin), itsValueItEnd(end), itsIndex(0), itsType(Value)
  411. {
  412. if( std::distance( begin, end ) == 0 )
  413. itsType = Null_;
  414. }
  415. //! Advance to the next node
  416. Iterator & operator++()
  417. {
  418. ++itsIndex;
  419. return *this;
  420. }
  421. //! Get the value of the current node
  422. GenericValue const & value()
  423. {
  424. switch(itsType)
  425. {
  426. case Value : return itsValueItBegin[itsIndex];
  427. case Member: return itsMemberItBegin[itsIndex].value;
  428. default: throw cereal::Exception("JSONInputArchive internal error: null or empty iterator to object or array!");
  429. }
  430. }
  431. //! Get the name of the current node, or nullptr if it has no name
  432. const char * name() const
  433. {
  434. if( itsType == Member && (itsMemberItBegin + itsIndex) != itsMemberItEnd )
  435. return itsMemberItBegin[itsIndex].name.GetString();
  436. else
  437. return nullptr;
  438. }
  439. //! Adjust our position such that we are at the node with the given name
  440. /*! @throws Exception if no such named node exists */
  441. inline void search( const char * searchName )
  442. {
  443. const auto len = std::strlen( searchName );
  444. size_t index = 0;
  445. for( auto it = itsMemberItBegin; it != itsMemberItEnd; ++it, ++index )
  446. {
  447. const auto currentName = it->name.GetString();
  448. if( ( std::strncmp( searchName, currentName, len ) == 0 ) &&
  449. ( std::strlen( currentName ) == len ) )
  450. {
  451. itsIndex = index;
  452. return;
  453. }
  454. }
  455. throw Exception("JSON Parsing failed - provided NVP (" + std::string(searchName) + ") not found");
  456. }
  457. private:
  458. MemberIterator itsMemberItBegin, itsMemberItEnd; //!< The member iterator (object)
  459. ValueIterator itsValueItBegin, itsValueItEnd; //!< The value iterator (array)
  460. size_t itsIndex; //!< The current index of this iterator
  461. enum Type {Value, Member, Null_} itsType; //!< Whether this holds values (array) or members (objects) or nothing
  462. };
  463. //! Searches for the expectedName node if it doesn't match the actualName
  464. /*! This needs to be called before every load or node start occurs. This function will
  465. check to see if an NVP has been provided (with setNextName) and if so, see if that name matches the actual
  466. next name given. If the names do not match, it will search in the current level of the JSON for that name.
  467. If the name is not found, an exception will be thrown.
  468. Resets the NVP name after called.
  469. @throws Exception if an expectedName is given and not found */
  470. inline void search()
  471. {
  472. // The name an NVP provided with setNextName()
  473. if( itsNextName )
  474. {
  475. // The actual name of the current node
  476. auto const actualName = itsIteratorStack.back().name();
  477. // Do a search if we don't see a name coming up, or if the names don't match
  478. if( !actualName || std::strcmp( itsNextName, actualName ) != 0 )
  479. itsIteratorStack.back().search( itsNextName );
  480. }
  481. itsNextName = nullptr;
  482. }
  483. public:
  484. //! Starts a new node, going into its proper iterator
  485. /*! This places an iterator for the next node to be parsed onto the iterator stack. If the next
  486. node is an array, this will be a value iterator, otherwise it will be a member iterator.
  487. By default our strategy is to start with the document root node and then recursively iterate through
  488. all children in the order they show up in the document.
  489. We don't need to know NVPs to do this; we'll just blindly load in the order things appear in.
  490. If we were given an NVP, we will search for it if it does not match our the name of the next node
  491. that would normally be loaded. This functionality is provided by search(). */
  492. void startNode()
  493. {
  494. search();
  495. if(itsIteratorStack.back().value().IsArray())
  496. itsIteratorStack.emplace_back(itsIteratorStack.back().value().Begin(), itsIteratorStack.back().value().End());
  497. else
  498. itsIteratorStack.emplace_back(itsIteratorStack.back().value().MemberBegin(), itsIteratorStack.back().value().MemberEnd());
  499. }
  500. //! Finishes the most recently started node
  501. void finishNode()
  502. {
  503. itsIteratorStack.pop_back();
  504. ++itsIteratorStack.back();
  505. }
  506. //! Retrieves the current node name
  507. /*! @return nullptr if no name exists */
  508. const char * getNodeName() const
  509. {
  510. return itsIteratorStack.back().name();
  511. }
  512. //! Sets the name for the next node created with startNode
  513. void setNextName( const char * name )
  514. {
  515. itsNextName = name;
  516. }
  517. //! Loads a value from the current node - small signed overload
  518. template <class T, traits::EnableIf<std::is_signed<T>::value,
  519. sizeof(T) < sizeof(int64_t)> = traits::sfinae> inline
  520. void loadValue(T & val)
  521. {
  522. search();
  523. val = static_cast<T>( itsIteratorStack.back().value().GetInt() );
  524. ++itsIteratorStack.back();
  525. }
  526. //! Loads a value from the current node - small unsigned overload
  527. template <class T, traits::EnableIf<std::is_unsigned<T>::value,
  528. sizeof(T) < sizeof(uint64_t),
  529. !std::is_same<bool, T>::value> = traits::sfinae> inline
  530. void loadValue(T & val)
  531. {
  532. search();
  533. val = static_cast<T>( itsIteratorStack.back().value().GetUint() );
  534. ++itsIteratorStack.back();
  535. }
  536. //! Loads a value from the current node - bool overload
  537. void loadValue(bool & val) { search(); val = itsIteratorStack.back().value().GetBool(); ++itsIteratorStack.back(); }
  538. //! Loads a value from the current node - int64 overload
  539. void loadValue(int64_t & val) { search(); val = itsIteratorStack.back().value().GetInt64(); ++itsIteratorStack.back(); }
  540. //! Loads a value from the current node - uint64 overload
  541. void loadValue(uint64_t & val) { search(); val = itsIteratorStack.back().value().GetUint64(); ++itsIteratorStack.back(); }
  542. //! Loads a value from the current node - float overload
  543. void loadValue(float & val) { search(); val = static_cast<float>(itsIteratorStack.back().value().GetDouble()); ++itsIteratorStack.back(); }
  544. //! Loads a value from the current node - double overload
  545. void loadValue(double & val) { search(); val = itsIteratorStack.back().value().GetDouble(); ++itsIteratorStack.back(); }
  546. //! Loads a value from the current node - string overload
  547. void loadValue(std::string & val) { search(); val = itsIteratorStack.back().value().GetString(); ++itsIteratorStack.back(); }
  548. //! Loads a nullptr from the current node
  549. void loadValue(std::nullptr_t&) { search(); CEREAL_RAPIDJSON_ASSERT(itsIteratorStack.back().value().IsNull()); ++itsIteratorStack.back(); }
  550. // Special cases to handle various flavors of long, which tend to conflict with
  551. // the int32_t or int64_t on various compiler/OS combinations. MSVC doesn't need any of this.
  552. #ifndef _MSC_VER
  553. private:
  554. //! 32 bit signed long loading from current node
  555. template <class T> inline
  556. typename std::enable_if<sizeof(T) == sizeof(std::int32_t) && std::is_signed<T>::value, void>::type
  557. loadLong(T & l){ loadValue( reinterpret_cast<std::int32_t&>( l ) ); }
  558. //! non 32 bit signed long loading from current node
  559. template <class T> inline
  560. typename std::enable_if<sizeof(T) == sizeof(std::int64_t) && std::is_signed<T>::value, void>::type
  561. loadLong(T & l){ loadValue( reinterpret_cast<std::int64_t&>( l ) ); }
  562. //! 32 bit unsigned long loading from current node
  563. template <class T> inline
  564. typename std::enable_if<sizeof(T) == sizeof(std::uint32_t) && !std::is_signed<T>::value, void>::type
  565. loadLong(T & lu){ loadValue( reinterpret_cast<std::uint32_t&>( lu ) ); }
  566. //! non 32 bit unsigned long loading from current node
  567. template <class T> inline
  568. typename std::enable_if<sizeof(T) == sizeof(std::uint64_t) && !std::is_signed<T>::value, void>::type
  569. loadLong(T & lu){ loadValue( reinterpret_cast<std::uint64_t&>( lu ) ); }
  570. public:
  571. //! Serialize a long if it would not be caught otherwise
  572. template <class T> inline
  573. typename std::enable_if<std::is_same<T, long>::value &&
  574. sizeof(T) >= sizeof(std::int64_t) &&
  575. !std::is_same<T, std::int64_t>::value, void>::type
  576. loadValue( T & t ){ loadLong(t); }
  577. //! Serialize an unsigned long if it would not be caught otherwise
  578. template <class T> inline
  579. typename std::enable_if<std::is_same<T, unsigned long>::value &&
  580. sizeof(T) >= sizeof(std::uint64_t) &&
  581. !std::is_same<T, std::uint64_t>::value, void>::type
  582. loadValue( T & t ){ loadLong(t); }
  583. #endif // _MSC_VER
  584. private:
  585. //! Convert a string to a long long
  586. void stringToNumber( std::string const & str, long long & val ) { val = std::stoll( str ); }
  587. //! Convert a string to an unsigned long long
  588. void stringToNumber( std::string const & str, unsigned long long & val ) { val = std::stoull( str ); }
  589. //! Convert a string to a long double
  590. void stringToNumber( std::string const & str, long double & val ) { val = std::stold( str ); }
  591. public:
  592. //! Loads a value from the current node - long double and long long overloads
  593. template <class T, traits::EnableIf<std::is_arithmetic<T>::value,
  594. !std::is_same<T, long>::value,
  595. !std::is_same<T, unsigned long>::value,
  596. !std::is_same<T, std::int64_t>::value,
  597. !std::is_same<T, std::uint64_t>::value,
  598. (sizeof(T) >= sizeof(long double) || sizeof(T) >= sizeof(long long))> = traits::sfinae>
  599. inline void loadValue(T & val)
  600. {
  601. std::string encoded;
  602. loadValue( encoded );
  603. stringToNumber( encoded, val );
  604. }
  605. //! Loads the size for a SizeTag
  606. void loadSize(size_type & size)
  607. {
  608. if (itsIteratorStack.size() == 1)
  609. size = itsDocument.Size();
  610. else
  611. size = (itsIteratorStack.rbegin() + 1)->value().Size();
  612. }
  613. //! @}
  614. private:
  615. const char * itsNextName; //!< Next name set by NVP
  616. ReadStream itsReadStream; //!< Rapidjson write stream
  617. std::vector<Iterator> itsIteratorStack; //!< 'Stack' of rapidJSON iterators
  618. CEREAL_RAPIDJSON_NAMESPACE::Document itsDocument; //!< Rapidjson document
  619. };
  620. // ######################################################################
  621. // JSONArchive prologue and epilogue functions
  622. // ######################################################################
  623. // ######################################################################
  624. //! Prologue for NVPs for JSON archives
  625. /*! NVPs do not start or finish nodes - they just set up the names */
  626. template <class T> inline
  627. void prologue( JSONOutputArchive &, NameValuePair<T> const & )
  628. { }
  629. //! Prologue for NVPs for JSON archives
  630. template <class T> inline
  631. void prologue( JSONInputArchive &, NameValuePair<T> const & )
  632. { }
  633. // ######################################################################
  634. //! Epilogue for NVPs for JSON archives
  635. /*! NVPs do not start or finish nodes - they just set up the names */
  636. template <class T> inline
  637. void epilogue( JSONOutputArchive &, NameValuePair<T> const & )
  638. { }
  639. //! Epilogue for NVPs for JSON archives
  640. /*! NVPs do not start or finish nodes - they just set up the names */
  641. template <class T> inline
  642. void epilogue( JSONInputArchive &, NameValuePair<T> const & )
  643. { }
  644. // ######################################################################
  645. //! Prologue for SizeTags for JSON archives
  646. /*! SizeTags are strictly ignored for JSON, they just indicate
  647. that the current node should be made into an array */
  648. template <class T> inline
  649. void prologue( JSONOutputArchive & ar, SizeTag<T> const & )
  650. {
  651. ar.makeArray();
  652. }
  653. //! Prologue for SizeTags for JSON archives
  654. template <class T> inline
  655. void prologue( JSONInputArchive &, SizeTag<T> const & )
  656. { }
  657. // ######################################################################
  658. //! Epilogue for SizeTags for JSON archives
  659. /*! SizeTags are strictly ignored for JSON */
  660. template <class T> inline
  661. void epilogue( JSONOutputArchive &, SizeTag<T> const & )
  662. { }
  663. //! Epilogue for SizeTags for JSON archives
  664. template <class T> inline
  665. void epilogue( JSONInputArchive &, SizeTag<T> const & )
  666. { }
  667. // ######################################################################
  668. //! Prologue for all other types for JSON archives (except minimal types)
  669. /*! Starts a new node, named either automatically or by some NVP,
  670. that may be given data by the type about to be archived
  671. Minimal types do not start or finish nodes */
  672. template <class T, traits::EnableIf<!std::is_arithmetic<T>::value,
  673. !traits::has_minimal_base_class_serialization<T, traits::has_minimal_output_serialization, JSONOutputArchive>::value,
  674. !traits::has_minimal_output_serialization<T, JSONOutputArchive>::value> = traits::sfinae>
  675. inline void prologue( JSONOutputArchive & ar, T const & )
  676. {
  677. ar.startNode();
  678. }
  679. //! Prologue for all other types for JSON archives
  680. template <class T, traits::EnableIf<!std::is_arithmetic<T>::value,
  681. !traits::has_minimal_base_class_serialization<T, traits::has_minimal_input_serialization, JSONInputArchive>::value,
  682. !traits::has_minimal_input_serialization<T, JSONInputArchive>::value> = traits::sfinae>
  683. inline void prologue( JSONInputArchive & ar, T const & )
  684. {
  685. ar.startNode();
  686. }
  687. // ######################################################################
  688. //! Epilogue for all other types other for JSON archives (except minimal types)
  689. /*! Finishes the node created in the prologue
  690. Minimal types do not start or finish nodes */
  691. template <class T, traits::EnableIf<!std::is_arithmetic<T>::value,
  692. !traits::has_minimal_base_class_serialization<T, traits::has_minimal_output_serialization, JSONOutputArchive>::value,
  693. !traits::has_minimal_output_serialization<T, JSONOutputArchive>::value> = traits::sfinae>
  694. inline void epilogue( JSONOutputArchive & ar, T const & )
  695. {
  696. ar.finishNode();
  697. }
  698. //! Epilogue for all other types other for JSON archives
  699. template <class T, traits::EnableIf<!std::is_arithmetic<T>::value,
  700. !traits::has_minimal_base_class_serialization<T, traits::has_minimal_input_serialization, JSONInputArchive>::value,
  701. !traits::has_minimal_input_serialization<T, JSONInputArchive>::value> = traits::sfinae>
  702. inline void epilogue( JSONInputArchive & ar, T const & )
  703. {
  704. ar.finishNode();
  705. }
  706. // ######################################################################
  707. //! Prologue for arithmetic types for JSON archives
  708. inline
  709. void prologue( JSONOutputArchive & ar, std::nullptr_t const & )
  710. {
  711. ar.writeName();
  712. }
  713. //! Prologue for arithmetic types for JSON archives
  714. inline
  715. void prologue( JSONInputArchive &, std::nullptr_t const & )
  716. { }
  717. // ######################################################################
  718. //! Epilogue for arithmetic types for JSON archives
  719. inline
  720. void epilogue( JSONOutputArchive &, std::nullptr_t const & )
  721. { }
  722. //! Epilogue for arithmetic types for JSON archives
  723. inline
  724. void epilogue( JSONInputArchive &, std::nullptr_t const & )
  725. { }
  726. // ######################################################################
  727. //! Prologue for arithmetic types for JSON archives
  728. template <class T, traits::EnableIf<std::is_arithmetic<T>::value> = traits::sfinae> inline
  729. void prologue( JSONOutputArchive & ar, T const & )
  730. {
  731. ar.writeName();
  732. }
  733. //! Prologue for arithmetic types for JSON archives
  734. template <class T, traits::EnableIf<std::is_arithmetic<T>::value> = traits::sfinae> inline
  735. void prologue( JSONInputArchive &, T const & )
  736. { }
  737. // ######################################################################
  738. //! Epilogue for arithmetic types for JSON archives
  739. template <class T, traits::EnableIf<std::is_arithmetic<T>::value> = traits::sfinae> inline
  740. void epilogue( JSONOutputArchive &, T const & )
  741. { }
  742. //! Epilogue for arithmetic types for JSON archives
  743. template <class T, traits::EnableIf<std::is_arithmetic<T>::value> = traits::sfinae> inline
  744. void epilogue( JSONInputArchive &, T const & )
  745. { }
  746. // ######################################################################
  747. //! Prologue for strings for JSON archives
  748. template<class CharT, class Traits, class Alloc> inline
  749. void prologue(JSONOutputArchive & ar, std::basic_string<CharT, Traits, Alloc> const &)
  750. {
  751. ar.writeName();
  752. }
  753. //! Prologue for strings for JSON archives
  754. template<class CharT, class Traits, class Alloc> inline
  755. void prologue(JSONInputArchive &, std::basic_string<CharT, Traits, Alloc> const &)
  756. { }
  757. // ######################################################################
  758. //! Epilogue for strings for JSON archives
  759. template<class CharT, class Traits, class Alloc> inline
  760. void epilogue(JSONOutputArchive &, std::basic_string<CharT, Traits, Alloc> const &)
  761. { }
  762. //! Epilogue for strings for JSON archives
  763. template<class CharT, class Traits, class Alloc> inline
  764. void epilogue(JSONInputArchive &, std::basic_string<CharT, Traits, Alloc> const &)
  765. { }
  766. // ######################################################################
  767. // Common JSONArchive serialization functions
  768. // ######################################################################
  769. //! Serializing NVP types to JSON
  770. template <class T> inline
  771. void CEREAL_SAVE_FUNCTION_NAME( JSONOutputArchive & ar, NameValuePair<T> const & t )
  772. {
  773. ar.setNextName( t.name );
  774. ar( t.value );
  775. }
  776. template <class T> inline
  777. void CEREAL_LOAD_FUNCTION_NAME( JSONInputArchive & ar, NameValuePair<T> & t )
  778. {
  779. ar.setNextName( t.name );
  780. ar( t.value );
  781. }
  782. //! Saving for nullptr to JSON
  783. inline
  784. void CEREAL_SAVE_FUNCTION_NAME(JSONOutputArchive & ar, std::nullptr_t const & t)
  785. {
  786. ar.saveValue( t );
  787. }
  788. //! Loading arithmetic from JSON
  789. inline
  790. void CEREAL_LOAD_FUNCTION_NAME(JSONInputArchive & ar, std::nullptr_t & t)
  791. {
  792. ar.loadValue( t );
  793. }
  794. //! Saving for arithmetic to JSON
  795. template <class T, traits::EnableIf<std::is_arithmetic<T>::value> = traits::sfinae> inline
  796. void CEREAL_SAVE_FUNCTION_NAME(JSONOutputArchive & ar, T const & t)
  797. {
  798. ar.saveValue( t );
  799. }
  800. //! Loading arithmetic from JSON
  801. template <class T, traits::EnableIf<std::is_arithmetic<T>::value> = traits::sfinae> inline
  802. void CEREAL_LOAD_FUNCTION_NAME(JSONInputArchive & ar, T & t)
  803. {
  804. ar.loadValue( t );
  805. }
  806. //! saving string to JSON
  807. template<class CharT, class Traits, class Alloc> inline
  808. void CEREAL_SAVE_FUNCTION_NAME(JSONOutputArchive & ar, std::basic_string<CharT, Traits, Alloc> const & str)
  809. {
  810. ar.saveValue( str );
  811. }
  812. //! loading string from JSON
  813. template<class CharT, class Traits, class Alloc> inline
  814. void CEREAL_LOAD_FUNCTION_NAME(JSONInputArchive & ar, std::basic_string<CharT, Traits, Alloc> & str)
  815. {
  816. ar.loadValue( str );
  817. }
  818. // ######################################################################
  819. //! Saving SizeTags to JSON
  820. template <class T> inline
  821. void CEREAL_SAVE_FUNCTION_NAME( JSONOutputArchive &, SizeTag<T> const & )
  822. {
  823. // nothing to do here, we don't explicitly save the size
  824. }
  825. //! Loading SizeTags from JSON
  826. template <class T> inline
  827. void CEREAL_LOAD_FUNCTION_NAME( JSONInputArchive & ar, SizeTag<T> & st )
  828. {
  829. ar.loadSize( st.size );
  830. }
  831. } // namespace cereal
  832. // register archives for polymorphic support
  833. CEREAL_REGISTER_ARCHIVE(cereal::JSONInputArchive)
  834. CEREAL_REGISTER_ARCHIVE(cereal::JSONOutputArchive)
  835. // tie input and output archives together
  836. CEREAL_SETUP_ARCHIVE_TRAITS(cereal::JSONInputArchive, cereal::JSONOutputArchive)
  837. #endif // CEREAL_ARCHIVES_JSON_HPP_