diff options
author | Your Name <you@example.com> | 2021-05-09 19:01:59 -0400 |
---|---|---|
committer | Your Name <you@example.com> | 2021-05-09 19:01:59 -0400 |
commit | e044fc4255aa64ef1dbc3d20ed87ed6e2f61a6bd (patch) | |
tree | 344c09421c5839a764a132fe9166f0e6e3f90e45 /src/utils.h | |
parent | d13358b71ec15085f2638fd9c3fc634df62dfc94 (diff) | |
download | dmtool-e044fc4255aa64ef1dbc3d20ed87ed6e2f61a6bd.tar.gz dmtool-e044fc4255aa64ef1dbc3d20ed87ed6e2f61a6bd.tar.bz2 dmtool-e044fc4255aa64ef1dbc3d20ed87ed6e2f61a6bd.zip |
Code refactoring
Diffstat (limited to 'src/utils.h')
-rw-r--r-- | src/utils.h | 29 |
1 files changed, 24 insertions, 5 deletions
diff --git a/src/utils.h b/src/utils.h index 71041a7..005e5be 100644 --- a/src/utils.h +++ b/src/utils.h @@ -1,6 +1,7 @@ #pragma once -#include "json.hpp" +#include <nlohmann/json.hpp> #include "entry.h" +#include "defines.h" #include <string> #include <vector> #include <map> @@ -9,6 +10,21 @@ #include <stdexcept> #include <filesystem> +namespace nlohmann { + template <typename T> struct adl_serializer<std::shared_ptr<T>> { + static void to_json(json& j, const std::shared_ptr<T>& opt) { + if(opt) { + j = opt->serialize(); + } else { + j = nullptr; + } + } + static void from_json(const json& j, std::shared_ptr<T>& opt) { + opt = std::shared_ptr<T>(T::create(j)); + } + }; +} + namespace utils { nlohmann::json loadJson(const std::filesystem::path& path); @@ -48,13 +64,17 @@ namespace utils { int parseInt(const std::string& s); template<typename S, typename D> std::shared_ptr<S> loadDFromJson(const nlohmann::json& data) { + nlohmann::json j = data; try { - return std::shared_ptr<S>(new D(loadJson(data["type"], data["name"]), data)); + j = loadJson(data["type"], data["name"]); } catch(std::exception& e) { // Covers errors in building the creature or fs traversal. // Fall back on the data passed in. - return std::shared_ptr<S>(new D(data, data)); } + D *d = new D(); + from_json(j, *d); + d->init(); + return std::shared_ptr<S>(d); } template<typename F, typename T> std::vector<std::shared_ptr<T>> castPtrs(std::vector<std::shared_ptr<F>> from) { @@ -109,8 +129,7 @@ namespace utils { template<typename T> std::vector<std::shared_ptr<T>> instantiateNames(const std::string& type, const std::vector<std::string>& names) { std::vector<std::shared_ptr<T>> ret; for(auto name : names) { - auto j = utils::loadJson(type, name); - ret.push_back(std::shared_ptr<T>(new T(j, j))); + ret.push_back(loadDFromJson<T, T>(utils::loadJson(type, name))); } return ret; } |