JsonSerializeFormat.h 16 KB

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