JsonSerializeFormat.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /*
  2. * JsonSerializeFormat.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include "../JsonNode.h"
  12. #include "../CModHandler.h"
  13. #include "../VCMI_Lib.h"
  14. VCMI_LIB_NAMESPACE_BEGIN
  15. class JsonSerializeFormat;
  16. class JsonStructSerializer;
  17. class JsonArraySerializer;
  18. class DLL_LINKAGE IInstanceResolver
  19. {
  20. public:
  21. virtual ~IInstanceResolver(){};
  22. virtual si32 decode(const std::string & identifier) const = 0;
  23. virtual std::string encode(si32 identifier) const = 0;
  24. };
  25. class DLL_LINKAGE JsonSerializeHelper: public boost::noncopyable
  26. {
  27. public:
  28. JsonSerializeHelper(JsonSerializeHelper && other) noexcept;
  29. virtual ~JsonSerializeHelper();
  30. JsonSerializeFormat * operator->();
  31. protected:
  32. JsonSerializeHelper(JsonSerializeFormat * owner_);
  33. JsonSerializeFormat * owner;
  34. private:
  35. bool restoreState;
  36. };
  37. class DLL_LINKAGE JsonStructSerializer: public JsonSerializeHelper
  38. {
  39. public:
  40. JsonStructSerializer(JsonStructSerializer && other) noexcept;
  41. protected:
  42. JsonStructSerializer(JsonSerializeFormat * owner_);
  43. friend class JsonSerializeFormat;
  44. friend class JsonArraySerializer;
  45. };
  46. class DLL_LINKAGE JsonArraySerializer: public JsonSerializeHelper
  47. {
  48. public:
  49. JsonArraySerializer(JsonArraySerializer && other) noexcept;
  50. JsonStructSerializer enterStruct(const size_t index);
  51. JsonArraySerializer enterArray(const size_t index);
  52. template <typename Container>
  53. void syncSize(Container & c, JsonNode::JsonType type = JsonNode::JsonType::DATA_NULL);
  54. ///Anything int64-convertible <-> Json integer
  55. template <typename T>
  56. void serializeInt(const size_t index, T & value);
  57. ///String <-> Json string
  58. void serializeString(const size_t index, std::string & value);
  59. ///vector of serializable <-> Json vector of structs
  60. template <typename Element>
  61. void serializeStruct(std::vector<Element> & value)
  62. {
  63. syncSize(value, JsonNode::JsonType::DATA_STRUCT);
  64. for(size_t idx = 0; idx < size(); idx++)
  65. {
  66. auto s = enterStruct(idx);
  67. value[idx].serializeJson(*owner);
  68. }
  69. }
  70. void resize(const size_t newSize);
  71. void resize(const size_t newSize, JsonNode::JsonType type);
  72. size_t size() const;
  73. protected:
  74. JsonArraySerializer(JsonSerializeFormat * owner_);
  75. friend class JsonSerializeFormat;
  76. private:
  77. const JsonNode * thisNode;
  78. void serializeInt64(const size_t index, int64_t & value);
  79. };
  80. class DLL_LINKAGE JsonSerializeFormat: public boost::noncopyable
  81. {
  82. public:
  83. ///user-provided callback to resolve string identifier
  84. ///returns resolved identifier or -1 on error
  85. using TDecoder = std::function<si32(const std::string &)>;
  86. ///user-provided callback to get string identifier
  87. ///may assume that object index is valid
  88. using TEncoder = std::function<std::string(si32)>;
  89. using TSerialize = std::function<void(JsonSerializeFormat &)>;
  90. struct LIC
  91. {
  92. LIC(const std::vector<bool> & Standard, TDecoder Decoder, TEncoder Encoder);
  93. const std::vector<bool> & standard;
  94. const TDecoder decoder;
  95. const TEncoder encoder;
  96. std::vector<bool> all, any, none;
  97. };
  98. struct LICSet
  99. {
  100. LICSet(const std::set<si32> & Standard, TDecoder Decoder, TEncoder Encoder);
  101. const std::set<si32> & standard;
  102. const TDecoder decoder;
  103. const TEncoder encoder;
  104. std::set<si32> all, any, none;
  105. };
  106. const bool saving;
  107. const bool updating;
  108. JsonSerializeFormat() = delete;
  109. virtual ~JsonSerializeFormat() = default;
  110. virtual const JsonNode & getCurrent() = 0;
  111. JsonStructSerializer enterStruct(const std::string & fieldName);
  112. JsonArraySerializer enterArray(const std::string & fieldName);
  113. ///Anything comparable <-> Json bool
  114. template <typename T>
  115. void serializeBool(const std::string & fieldName, T & value, const T trueValue, const T falseValue, const T defaultValue)
  116. {
  117. boost::logic::tribool temp(boost::logic::indeterminate);
  118. if(value == defaultValue)
  119. ;//leave as indeterminate
  120. else if(value == trueValue)
  121. temp = true;
  122. else if(value == falseValue)
  123. temp = false;
  124. serializeInternal(fieldName, temp);
  125. if(!saving)
  126. {
  127. if(boost::logic::indeterminate(temp))
  128. value = defaultValue;
  129. else
  130. value = temp ? trueValue : falseValue;
  131. }
  132. }
  133. ///bool <-> Json bool
  134. void serializeBool(const std::string & fieldName, bool & value);
  135. void serializeBool(const std::string & fieldName, bool & value, const bool defaultValue);
  136. ///tribool <-> Json bool
  137. void serializeBool(const std::string & fieldName, boost::logic::tribool & value)
  138. {
  139. serializeInternal(fieldName, value);
  140. };
  141. /** @brief Restrictive ("anyOf") simple serialization of Logical identifier condition, simple deserialization (allOf=anyOf)
  142. *
  143. * @param fieldName
  144. * @param decoder resolve callback, should report errors itself and do not throw
  145. * @param encoder encode callback, should report errors itself and do not throw
  146. * @param value target value, must be resized properly
  147. *
  148. */
  149. virtual void serializeLIC(const std::string & fieldName, const TDecoder & decoder, const TEncoder & encoder, const std::vector<bool> & standard, std::vector<bool> & value) = 0;
  150. /** @brief Complete serialization of Logical identifier condition
  151. */
  152. virtual void serializeLIC(const std::string & fieldName, LIC & value) = 0;
  153. /** @brief Complete serialization of Logical identifier condition. (Special version)
  154. * Assumes that all values are allowed by default, and standard contains them
  155. */
  156. virtual void serializeLIC(const std::string & fieldName, LICSet & value) = 0;
  157. ///String <-> Json string
  158. virtual void serializeString(const std::string & fieldName, std::string & value) = 0;
  159. ///si32-convertible enum <-> Json string enum
  160. template <typename T>
  161. void serializeEnum(const std::string & fieldName, T & value, const std::vector<std::string> & enumMap)
  162. {
  163. doSerializeInternal<T, T, si32>(fieldName, value, std::nullopt, enumMap);
  164. };
  165. ///si32-convertible enum <-> Json string enum
  166. template <typename T, typename U>
  167. void serializeEnum(const std::string & fieldName, T & value, const U & defaultValue, const std::vector<std::string> & enumMap)
  168. {
  169. doSerializeInternal<T, U, si32>(fieldName, value, defaultValue, enumMap);
  170. };
  171. template <typename T, typename U, typename C>
  172. void serializeEnum(const std::string & fieldName, T & value, const U & defaultValue, const C & enumMap)
  173. {
  174. std::vector<std::string> enumMapCopy;
  175. std::copy(std::begin(enumMap), std::end(enumMap), std::back_inserter(enumMapCopy));
  176. doSerializeInternal<T, U, si32>(fieldName, value, defaultValue, enumMapCopy);
  177. };
  178. ///Anything double-convertible <-> Json double
  179. template <typename T>
  180. void serializeFloat(const std::string & fieldName, T & value)
  181. {
  182. doSerializeInternal<T, T, double>(fieldName, value, std::nullopt);
  183. };
  184. ///Anything double-convertible <-> Json double
  185. template <typename T, typename U>
  186. void serializeFloat(const std::string & fieldName, T & value, const U & defaultValue)
  187. {
  188. doSerializeInternal<T, U, double>(fieldName, value, defaultValue);
  189. };
  190. ///Anything int64-convertible <-> Json integer
  191. ///no default value
  192. template <typename T>
  193. void serializeInt(const std::string & fieldName, T & value)
  194. {
  195. doSerializeInternal<T, T, si64>(fieldName, value, std::nullopt);
  196. };
  197. ///Anything int64-convertible <-> Json integer
  198. ///custom default value
  199. template <typename T, typename U>
  200. void serializeInt(const std::string & fieldName, T & value, const U & defaultValue)
  201. {
  202. doSerializeInternal<T, U, si64>(fieldName, value, defaultValue);
  203. };
  204. ///Anything int64-convertible <-> Json integer
  205. ///default value is std::nullopt
  206. template<typename T>
  207. void serializeInt(const std::string & fieldName, std::optional<T> & value)
  208. {
  209. dispatchOptional<T, si64>(fieldName, value);
  210. };
  211. ///si32-convertible identifier <-> Json string
  212. template <typename T, typename U>
  213. void serializeId(const std::string & fieldName, T & value, const U & defaultValue, const TDecoder & decoder, const TEncoder & encoder)
  214. {
  215. doSerializeInternal<T, U, si32>(fieldName, value, defaultValue, decoder, encoder);
  216. }
  217. ///si32-convertible identifier <-> Json string
  218. template <typename T, typename U, typename E = T>
  219. void serializeId(const std::string & fieldName, T & value, const U & defaultValue)
  220. {
  221. doSerializeInternal<T, U, si32>(fieldName, value, defaultValue, &E::decode, &E::encode);
  222. }
  223. ///si32-convertible identifier vector <-> Json array of string
  224. template <typename T, typename E = T>
  225. void serializeIdArray(const std::string & fieldName, std::vector<T> & value)
  226. {
  227. std::vector<si32> temp;
  228. if(saving)
  229. {
  230. temp.reserve(value.size());
  231. for(const T & vitem : value)
  232. {
  233. si32 item = static_cast<si32>(vitem);
  234. temp.push_back(item);
  235. }
  236. }
  237. serializeInternal(fieldName, temp, &E::decode, &E::encode);
  238. if(!saving)
  239. {
  240. value.clear();
  241. value.reserve(temp.size());
  242. for(const si32 item : temp)
  243. {
  244. T vitem = static_cast<T>(item);
  245. value.push_back(vitem);
  246. }
  247. }
  248. }
  249. ///si32-convertible identifier set <-> Json array of string
  250. template <typename T, typename U = T>
  251. void serializeIdArray(const std::string & fieldName, std::set<T> & value)
  252. {
  253. std::vector<si32> temp;
  254. if(saving)
  255. {
  256. temp.reserve(value.size());
  257. for(const T & vitem : value)
  258. {
  259. si32 item = static_cast<si32>(vitem);
  260. temp.push_back(item);
  261. }
  262. }
  263. serializeInternal(fieldName, temp, &U::decode, &U::encode);
  264. if(!saving)
  265. {
  266. value.clear();
  267. for(const si32 item : temp)
  268. {
  269. T vitem = static_cast<T>(item);
  270. value.insert(vitem);
  271. }
  272. }
  273. }
  274. ///si32-convertible identifier set <-> Json array of string
  275. ///Type U is only used for code & decode
  276. ///TODO: Auto deduce U based on T?
  277. template <typename T, typename U = T>
  278. void serializeIdArray(const std::string & fieldName, std::set<T> & value, const std::set<T> & defaultValue)
  279. {
  280. std::vector<si32> temp;
  281. if(saving && value != defaultValue)
  282. {
  283. temp.reserve(value.size());
  284. for(const T & vitem : value)
  285. {
  286. si32 item = static_cast<si32>(vitem);
  287. temp.push_back(item);
  288. }
  289. serializeInternal(fieldName, temp, &U::decode, &U::encode);
  290. }
  291. if(!saving)
  292. {
  293. JsonNode node;
  294. serializeRaw(fieldName, node, std::nullopt);
  295. if(node.Vector().empty())
  296. {
  297. value = defaultValue;
  298. }
  299. else
  300. {
  301. value.clear();
  302. for(const auto & id : node.Vector())
  303. {
  304. VLC->modh->identifiers.requestIdentifier(U::entityType(), id, [&value](int32_t identifier)
  305. {
  306. value.emplace(identifier);
  307. });
  308. }
  309. }
  310. }
  311. }
  312. ///bitmask <-> Json array of string
  313. template <typename T, int Size>
  314. void serializeIdArray(const std::string & fieldName, T & value, const T & defaultValue, const TDecoder & decoder, const TEncoder & encoder)
  315. {
  316. static_assert(8 * sizeof(T) >= Size, "Mask size too small");
  317. std::vector<si32> temp;
  318. temp.reserve(Size);
  319. if(saving && value != defaultValue)
  320. {
  321. for(si32 i = 0; i < Size; i++)
  322. if(value & (1 << i))
  323. temp.push_back(i);
  324. serializeInternal(fieldName, temp, decoder, encoder);
  325. }
  326. if(!saving)
  327. {
  328. serializeInternal(fieldName, temp, decoder, encoder);
  329. if(temp.empty())
  330. value = defaultValue;
  331. else
  332. {
  333. value = 0;
  334. for(auto i : temp)
  335. value |= (1 << i);
  336. }
  337. }
  338. }
  339. ///si32-convertible instance identifier <-> Json string
  340. template <typename T>
  341. void serializeInstance(const std::string & fieldName, T & value, const T & defaultValue)
  342. {
  343. const TDecoder decoder = std::bind(&IInstanceResolver::decode, instanceResolver, _1);
  344. const TEncoder endoder = std::bind(&IInstanceResolver::encode, instanceResolver, _1);
  345. serializeId<T>(fieldName, value, defaultValue, decoder, endoder);
  346. }
  347. ///any serializable object <-> Json struct
  348. template <typename T>
  349. void serializeStruct(const std::string & fieldName, T & value)
  350. {
  351. auto guard = enterStruct(fieldName);
  352. value.serializeJson(*this);
  353. }
  354. virtual void serializeRaw(const std::string & fieldName, JsonNode & value, const std::optional<std::reference_wrapper<const JsonNode>> defaultValue) = 0;
  355. protected:
  356. JsonSerializeFormat(const IInstanceResolver * instanceResolver_, const bool saving_, const bool updating_);
  357. ///bool <-> Json bool, indeterminate is default
  358. virtual void serializeInternal(const std::string & fieldName, boost::logic::tribool & value) = 0;
  359. ///Numeric Id <-> String Id
  360. virtual void serializeInternal(const std::string & fieldName, si32 & value, const std::optional<si32> & defaultValue, const TDecoder & decoder, const TEncoder & encoder) = 0;
  361. ///Numeric Id vector <-> String Id vector
  362. virtual void serializeInternal(const std::string & fieldName, std::vector<si32> & value, const TDecoder & decoder, const TEncoder & encoder) = 0;
  363. ///Numeric <-> Json double
  364. virtual void serializeInternal(const std::string & fieldName, double & value, const std::optional<double> & defaultValue) = 0;
  365. ///Numeric <-> Json integer
  366. virtual void serializeInternal(const std::string & fieldName, si64 & value, const std::optional<si64> & defaultValue) = 0;
  367. ///Enum/Numeric <-> Json string enum
  368. virtual void serializeInternal(const std::string & fieldName, si32 & value, const std::optional<si32> & defaultValue, const std::vector<std::string> & enumMap) = 0;
  369. virtual void pop() = 0;
  370. virtual void pushStruct(const std::string & fieldName) = 0;
  371. virtual void pushArray(const std::string & fieldName) = 0;
  372. virtual void pushArrayElement(const size_t index) = 0;
  373. virtual void pushField(const std::string & fieldName) = 0;
  374. virtual void resizeCurrent(const size_t newSize, JsonNode::JsonType type){};
  375. virtual void serializeInternal(std::string & value) = 0;
  376. virtual void serializeInternal(int64_t & value) = 0;
  377. private:
  378. const IInstanceResolver * instanceResolver;
  379. template<typename VType, typename DVType, typename IType, typename... Args>
  380. void doSerializeInternal(const std::string & fieldName, VType & value, const std::optional<DVType> & defaultValue, Args... args)
  381. {
  382. const std::optional<IType> tempDefault = defaultValue ? std::optional<IType>(static_cast<IType>(defaultValue.value())) : std::nullopt;
  383. auto temp = static_cast<IType>(value);
  384. serializeInternal(fieldName, temp, tempDefault, args...);
  385. if(!saving)
  386. value = static_cast<VType>(temp);
  387. }
  388. template<typename VType, typename IType, typename... Args>
  389. void dispatchOptional(const std::string & fieldName, std::optional<VType> & value, Args... args)
  390. {
  391. if(saving)
  392. {
  393. if(value)
  394. {
  395. auto temp = static_cast<IType>(value.value());
  396. pushField(fieldName);
  397. serializeInternal(temp, args...);
  398. pop();
  399. }
  400. }
  401. else
  402. {
  403. pushField(fieldName);
  404. if(getCurrent().getType() == JsonNode::JsonType::DATA_NULL)
  405. {
  406. value = std::nullopt;
  407. }
  408. else
  409. {
  410. IType temp = IType();
  411. serializeInternal(temp, args...);
  412. value = std::make_optional(temp);
  413. }
  414. pop();
  415. }
  416. }
  417. friend class JsonSerializeHelper;
  418. friend class JsonStructSerializer;
  419. friend class JsonArraySerializer;
  420. };
  421. template <typename Container>
  422. void JsonArraySerializer::syncSize(Container & c, JsonNode::JsonType type)
  423. {
  424. if(owner->saving)
  425. resize(c.size(), type);
  426. else
  427. c.resize(size());
  428. }
  429. template <typename T>
  430. void JsonArraySerializer::serializeInt(const size_t index, T & value)
  431. {
  432. auto temp = static_cast<int64_t>(value);
  433. serializeInt64(index, temp);
  434. if (!owner->saving)
  435. value = static_cast<T>(temp);
  436. };
  437. VCMI_LIB_NAMESPACE_END