From a62bd981c2a973952f3f5e22ca768dd961991d21 Mon Sep 17 00:00:00 2001 From: Stanislaw Halik Date: Sun, 23 Oct 2022 11:59:24 +0200 Subject: allow serializing empty shared_ptr --- serialize/tile-atlas.cpp | 17 ++++++++++++----- serialize/world.cpp | 16 ++++++++++------ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/serialize/tile-atlas.cpp b/serialize/tile-atlas.cpp index d5350851..fcbb371d 100644 --- a/serialize/tile-atlas.cpp +++ b/serialize/tile-atlas.cpp @@ -15,16 +15,23 @@ using proxy_atlas = std::tuple; void adl_serializer>::to_json(json& j, const std::shared_ptr& x) { - fm_assert(x); using nlohmann::to_json; - to_json(j, proxy_atlas{x->name(), x->num_tiles2()}); + if (!x) + j = nullptr; + else + to_json(j, proxy_atlas{x->name(), x->num_tiles2()}); } void adl_serializer>::from_json(const json& j, std::shared_ptr& x) { - proxy_atlas proxy = j; - const auto& [name, num_tiles] = proxy; - x = loader.tile_atlas(name, num_tiles); + if (j.is_null()) + x = nullptr; + else + { + proxy_atlas proxy = j; + const auto& [name, num_tiles] = proxy; + x = loader.tile_atlas(name, num_tiles); + } } } // namespace nlohmann diff --git a/serialize/world.cpp b/serialize/world.cpp index 8b6f84d7..7bdf8ba6 100644 --- a/serialize/world.cpp +++ b/serialize/world.cpp @@ -26,10 +26,10 @@ NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(global_coords_, chunk, local) } // namespace floormat -using namespace floormat; - namespace nlohmann { +using namespace floormat; + template<> struct adl_serializer> final { static void to_json(json& j, const std::shared_ptr& x); @@ -38,16 +38,20 @@ struct adl_serializer> final { void adl_serializer>::to_json(json& j, const std::shared_ptr& val) { - fm_assert(val); using nlohmann::to_json; - j = *val; + if (!val) + j = nullptr; + else + j = *val; } void adl_serializer>::from_json(const json& j, std::shared_ptr& val) { - val = std::make_shared(); using nlohmann::from_json; - *val = j; + if (j.is_null()) + val = nullptr; + else + *(val = std::make_shared()) = j; } void adl_serializer::to_json(json& j, const chunk_coords& val) { using nlohmann::to_json; to_json(j, val); } -- cgit v1.2.3