From e044fc4255aa64ef1dbc3d20ed87ed6e2f61a6bd Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 9 May 2021 19:01:59 -0400 Subject: Code refactoring --- src/utils.h | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) (limited to 'src/utils.h') 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 #include "entry.h" +#include "defines.h" #include #include #include @@ -9,6 +10,21 @@ #include #include +namespace nlohmann { + template struct adl_serializer> { + static void to_json(json& j, const std::shared_ptr& opt) { + if(opt) { + j = opt->serialize(); + } else { + j = nullptr; + } + } + static void from_json(const json& j, std::shared_ptr& opt) { + opt = std::shared_ptr(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 std::shared_ptr loadDFromJson(const nlohmann::json& data) { + nlohmann::json j = data; try { - return std::shared_ptr(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(new D(data, data)); } + D *d = new D(); + from_json(j, *d); + d->init(); + return std::shared_ptr(d); } template std::vector> castPtrs(std::vector> from) { @@ -109,8 +129,7 @@ namespace utils { template std::vector> instantiateNames(const std::string& type, const std::vector& names) { std::vector> ret; for(auto name : names) { - auto j = utils::loadJson(type, name); - ret.push_back(std::shared_ptr(new T(j, j))); + ret.push_back(loadDFromJson(utils::loadJson(type, name))); } return ret; } -- cgit v1.2.3