JsonSerializeFormat.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. struct LICSet
  112. {
  113. LICSet(const std::set<si32> & Standard, TDecoder Decoder, TEncoder Encoder);
  114. const std::set<si32> & standard;
  115. const TDecoder decoder;
  116. const TEncoder encoder;
  117. std::set<si32> all, any, none;
  118. };
  119. const bool saving;
  120. const bool updating;
  121. JsonSerializeFormat() = delete;
  122. virtual ~JsonSerializeFormat() = default;
  123. virtual const JsonNode & getCurrent() = 0;
  124. JsonStructSerializer enterStruct(const std::string & fieldName);
  125. JsonArraySerializer enterArray(const std::string & fieldName);
  126. ///Anything comparable <-> Json bool
  127. template <typename T>
  128. void serializeBool(const std::string & fieldName, T & value, const T trueValue, const T falseValue, const T defaultValue)
  129. {
  130. boost::logic::tribool temp(boost::logic::indeterminate);
  131. if(value == defaultValue)
  132. ;//leave as indeterminate
  133. else if(value == trueValue)
  134. temp = true;
  135. else if(value == falseValue)
  136. temp = false;
  137. serializeInternal(fieldName, temp);
  138. if(!saving)
  139. {
  140. if(boost::logic::indeterminate(temp))
  141. value = defaultValue;
  142. else
  143. value = temp ? trueValue : falseValue;
  144. }
  145. }
  146. ///bool <-> Json bool
  147. void serializeBool(const std::string & fieldName, bool & value);
  148. void serializeBool(const std::string & fieldName, bool & value, const bool defaultValue);
  149. ///tribool <-> Json bool
  150. void serializeBool(const std::string & fieldName, boost::logic::tribool & value)
  151. {
  152. serializeInternal(fieldName, value);
  153. };
  154. /** @brief Restrictive ("anyOf") simple serialization of Logical identifier condition, simple deserialization (allOf=anyOf)
  155. *
  156. * @param fieldName
  157. * @param decoder resolve callback, should report errors itself and do not throw
  158. * @param encoder encode callback, should report errors itself and do not throw
  159. * @param value target value, must be resized properly
  160. *
  161. */
  162. virtual void serializeLIC(const std::string & fieldName, const TDecoder & decoder, const TEncoder & encoder, const std::set<int32_t> & standard, std::set<int32_t> & value) = 0;
  163. template<typename T>
  164. void serializeLIC(const std::string & fieldName, const TDecoder & decoder, const TEncoder & encoder, const std::set<T> & standard, std::set<T> & value)
  165. {
  166. std::set<int32_t> standardInt;
  167. std::set<int32_t> valueInt;
  168. for (auto entry : standard)
  169. standardInt.insert(entry.getNum());
  170. for (auto entry : value)
  171. valueInt.insert(entry.getNum());
  172. serializeLIC(fieldName, decoder, encoder, standard, value);
  173. value.clear();
  174. for (auto entry : valueInt)
  175. value.insert(T(entry));
  176. }
  177. /** @brief Complete serialization of Logical identifier condition.
  178. * Assumes that all values are allowed by default, and standard contains them
  179. */
  180. virtual void serializeLIC(const std::string & fieldName, LICSet & value) = 0;
  181. ///String <-> Json string
  182. virtual void serializeString(const std::string & fieldName, std::string & value) = 0;
  183. ///si32-convertible enum <-> Json string enum
  184. template <typename T>
  185. void serializeEnum(const std::string & fieldName, T & value, const std::vector<std::string> & enumMap)
  186. {
  187. doSerializeInternal<T, T, si32>(fieldName, value, std::nullopt, enumMap);
  188. };
  189. ///si32-convertible enum <-> Json string enum
  190. template <typename T, typename U>
  191. void serializeEnum(const std::string & fieldName, T & value, const U & defaultValue, const std::vector<std::string> & enumMap)
  192. {
  193. doSerializeInternal<T, U, si32>(fieldName, value, defaultValue, enumMap);
  194. };
  195. template <typename T, typename U, typename C>
  196. void serializeEnum(const std::string & fieldName, T & value, const U & defaultValue, const C & enumMap)
  197. {
  198. std::vector<std::string> enumMapCopy;
  199. std::copy(std::begin(enumMap), std::end(enumMap), std::back_inserter(enumMapCopy));
  200. doSerializeInternal<T, U, si32>(fieldName, value, defaultValue, enumMapCopy);
  201. };
  202. ///Anything double-convertible <-> Json double
  203. template <typename T>
  204. void serializeFloat(const std::string & fieldName, T & value)
  205. {
  206. doSerializeInternal<T, T, double>(fieldName, value, std::nullopt);
  207. };
  208. ///Anything double-convertible <-> Json double
  209. template <typename T, typename U>
  210. void serializeFloat(const std::string & fieldName, T & value, const U & defaultValue)
  211. {
  212. doSerializeInternal<T, U, double>(fieldName, value, defaultValue);
  213. };
  214. ///Anything int64-convertible <-> Json integer
  215. ///no default value
  216. template <typename T>
  217. void serializeInt(const std::string & fieldName, T & value)
  218. {
  219. doSerializeInternal<T, T, si64>(fieldName, value, std::nullopt);
  220. };
  221. ///Anything int64-convertible <-> Json integer
  222. ///custom default value
  223. template <typename T, typename U>
  224. void serializeInt(const std::string & fieldName, T & value, const U & defaultValue)
  225. {
  226. doSerializeInternal<T, U, si64>(fieldName, value, defaultValue);
  227. };
  228. ///Anything int64-convertible <-> Json integer
  229. ///default value is std::nullopt
  230. template<typename T>
  231. void serializeInt(const std::string & fieldName, std::optional<T> & value)
  232. {
  233. dispatchOptional<T, si64>(fieldName, value);
  234. };
  235. ///si32-convertible identifier <-> Json string
  236. template <typename T, typename U>
  237. void serializeId(const std::string & fieldName, T & value, const U & defaultValue, const TDecoder & decoder, const TEncoder & encoder)
  238. {
  239. doSerializeInternal<T, U, si32>(fieldName, value, defaultValue, decoder, encoder);
  240. }
  241. ///si32-convertible identifier <-> Json string
  242. template <typename IdentifierType, typename IdentifierTypeBase = IdentifierType>
  243. void serializeId(const std::string & fieldName, IdentifierType & value, const IdentifierTypeBase & defaultValue = IdentifierType::NONE)
  244. {
  245. static_assert(std::is_base_of_v<IdentifierBase, IdentifierType>, "This method can only serialize Identifier classes!");
  246. if (saving)
  247. {
  248. if (value != defaultValue)
  249. {
  250. std::string fieldValue = IdentifierType::encode(value.getNum());
  251. serializeString(fieldName, fieldValue);
  252. }
  253. }
  254. else
  255. {
  256. std::string fieldValue;
  257. serializeString(fieldName, fieldValue);
  258. if (!fieldValue.empty())
  259. {
  260. VLC->identifiers()->requestIdentifier(ModScope::scopeGame(), IdentifierType::entityType(), fieldValue, [&value](int32_t index){
  261. value = IdentifierType(index);
  262. });
  263. }
  264. else
  265. {
  266. value = IdentifierType(defaultValue);
  267. }
  268. }
  269. }
  270. ///si32-convertible identifier vector <-> Json array of string
  271. template <typename T, typename E = T>
  272. void serializeIdArray(const std::string & fieldName, std::vector<T> & value)
  273. {
  274. if (saving)
  275. {
  276. std::vector<std::string> fieldValue;
  277. for(const T & vitem : value)
  278. fieldValue.push_back(E::encode(vitem.getNum()));
  279. serializeInternal(fieldName, fieldValue);
  280. }
  281. else
  282. {
  283. std::vector<std::string> fieldValue;
  284. serializeInternal(fieldName, fieldValue);
  285. value.resize(fieldValue.size());
  286. for(size_t i = 0; i < fieldValue.size(); ++i)
  287. {
  288. VLC->identifiers()->requestIdentifier(ModScope::scopeGame(), E::entityType(), fieldValue[i], [&value, i](int32_t index){
  289. value[i] = T(index);
  290. });
  291. }
  292. }
  293. }
  294. ///si32-convertible identifier set <-> Json array of string
  295. template <typename T, typename U = T>
  296. void serializeIdArray(const std::string & fieldName, std::set<T> & value)
  297. {
  298. if (saving)
  299. {
  300. std::vector<std::string> fieldValue;
  301. for(const T & vitem : value)
  302. fieldValue.push_back(U::encode(vitem.getNum()));
  303. serializeInternal(fieldName, fieldValue);
  304. }
  305. else
  306. {
  307. std::vector<std::string> fieldValue;
  308. serializeInternal(fieldName, fieldValue);
  309. for(size_t i = 0; i < fieldValue.size(); ++i)
  310. {
  311. VLC->identifiers()->requestIdentifier(ModScope::scopeGame(), U::entityType(), fieldValue[i], [&value](int32_t index){
  312. value.insert(T(index));
  313. });
  314. }
  315. }
  316. }
  317. ///si32-convertible instance identifier <-> Json string
  318. template <typename T>
  319. void serializeInstance(const std::string & fieldName, T & value, const T & defaultValue)
  320. {
  321. const TDecoder decoder = std::bind(&IInstanceResolver::decode, instanceResolver, _1);
  322. const TEncoder encoder = std::bind(&IInstanceResolver::encode, instanceResolver, _1);
  323. if (saving)
  324. {
  325. if (value != defaultValue)
  326. {
  327. std::string fieldValue = encoder(value.getNum());
  328. serializeString(fieldName, fieldValue);
  329. }
  330. }
  331. else
  332. {
  333. std::string fieldValue;
  334. serializeString(fieldName, fieldValue);
  335. if (!fieldValue.empty())
  336. value = T(decoder(fieldValue));
  337. else
  338. value = T(defaultValue);
  339. }
  340. }
  341. ///any serializable object <-> Json struct
  342. template <typename T>
  343. void serializeStruct(const std::string & fieldName, T & value)
  344. {
  345. auto guard = enterStruct(fieldName);
  346. value.serializeJson(*this);
  347. }
  348. virtual void serializeRaw(const std::string & fieldName, JsonNode & value, const std::optional<std::reference_wrapper<const JsonNode>> defaultValue) = 0;
  349. protected:
  350. JsonSerializeFormat(const IInstanceResolver * instanceResolver_, const bool saving_, const bool updating_);
  351. ///bool <-> Json bool, indeterminate is default
  352. virtual void serializeInternal(const std::string & fieldName, boost::logic::tribool & value) = 0;
  353. ///Numeric Id <-> String Id
  354. virtual void serializeInternal(const std::string & fieldName, si32 & value, const std::optional<si32> & defaultValue, const TDecoder & decoder, const TEncoder & encoder) = 0;
  355. ///Numeric Id vector <-> String Id vector
  356. virtual void serializeInternal(const std::string & fieldName, std::vector<si32> & value, const TDecoder & decoder, const TEncoder & encoder) = 0;
  357. ///Numeric <-> Json double
  358. virtual void serializeInternal(const std::string & fieldName, double & value, const std::optional<double> & defaultValue) = 0;
  359. ///Numeric <-> Json integer
  360. virtual void serializeInternal(const std::string & fieldName, si64 & value, const std::optional<si64> & defaultValue) = 0;
  361. ///Enum/Numeric <-> Json string enum
  362. virtual void serializeInternal(const std::string & fieldName, si32 & value, const std::optional<si32> & defaultValue, const std::vector<std::string> & enumMap) = 0;
  363. ///String vector <-> Json string vector
  364. virtual void serializeInternal(const std::string & fieldName, std::vector<std::string> & value) = 0;
  365. virtual void pop() = 0;
  366. virtual void pushStruct(const std::string & fieldName) = 0;
  367. virtual void pushArray(const std::string & fieldName) = 0;
  368. virtual void pushArrayElement(const size_t index) = 0;
  369. virtual void pushField(const std::string & fieldName) = 0;
  370. virtual void resizeCurrent(const size_t newSize, JsonNode::JsonType type){};
  371. virtual void serializeInternal(std::string & value) = 0;
  372. virtual void serializeInternal(int64_t & value) = 0;
  373. void readLICPart(const JsonNode & part, const JsonSerializeFormat::TDecoder & decoder, std::set<si32> & value) const;
  374. private:
  375. const IInstanceResolver * instanceResolver;
  376. template<typename VType, typename DVType, typename IType, typename... Args>
  377. void doSerializeInternal(const std::string & fieldName, VType & value, const std::optional<DVType> & defaultValue, Args... args)
  378. {
  379. const std::optional<IType> tempDefault = defaultValue ? std::optional<IType>(static_cast<IType>(defaultValue.value())) : std::nullopt;
  380. auto temp = static_cast<IType>(value);
  381. serializeInternal(fieldName, temp, tempDefault, args...);
  382. if(!saving)
  383. value = static_cast<VType>(temp);
  384. }
  385. template<typename VType, typename IType, typename... Args>
  386. void dispatchOptional(const std::string & fieldName, std::optional<VType> & value, Args... args)
  387. {
  388. if(saving)
  389. {
  390. if(value)
  391. {
  392. auto temp = static_cast<IType>(value.value());
  393. pushField(fieldName);
  394. serializeInternal(temp, args...);
  395. pop();
  396. }
  397. }
  398. else
  399. {
  400. pushField(fieldName);
  401. if(getCurrent().getType() == JsonNode::JsonType::DATA_NULL)
  402. {
  403. value = std::nullopt;
  404. }
  405. else
  406. {
  407. IType temp = IType();
  408. serializeInternal(temp, args...);
  409. value = std::make_optional(temp);
  410. }
  411. pop();
  412. }
  413. }
  414. friend class JsonSerializeHelper;
  415. friend class JsonStructSerializer;
  416. friend class JsonArraySerializer;
  417. };
  418. template <typename Container>
  419. void JsonArraySerializer::syncSize(Container & c, JsonNode::JsonType type)
  420. {
  421. if(owner->saving)
  422. resize(c.size(), type);
  423. else
  424. c.resize(size());
  425. }
  426. template <typename T>
  427. void JsonArraySerializer::serializeInt(const size_t index, T & value)
  428. {
  429. auto temp = static_cast<int64_t>(value);
  430. serializeInt64(index, temp);
  431. if (!owner->saving)
  432. value = static_cast<T>(temp);
  433. };
  434. VCMI_LIB_NAMESPACE_END