JsonSerializeFormat.h 16 KB

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