summaryrefslogtreecommitdiffhomepage
path: root/serialize/vector.hpp
diff options
context:
space:
mode:
authorStanislaw Halik <sthalik@misaki.pl>2022-10-05 15:47:29 +0200
committerStanislaw Halik <sthalik@misaki.pl>2022-10-05 15:47:29 +0200
commit6731ab0243ba437595062558e56b800d5eca9cf5 (patch)
tree39025a8ca381ff6f71cbe316c7d72b32f506a9bf /serialize/vector.hpp
parent2c26d57dc97eb7105a6dca2089fd42847a8c2b37 (diff)
a
Diffstat (limited to 'serialize/vector.hpp')
-rw-r--r--serialize/vector.hpp41
1 files changed, 41 insertions, 0 deletions
diff --git a/serialize/vector.hpp b/serialize/vector.hpp
new file mode 100644
index 00000000..39924a9b
--- /dev/null
+++ b/serialize/vector.hpp
@@ -0,0 +1,41 @@
+#include <cstdio>
+#include <string>
+#include <exception>
+#include <Magnum/Magnum.h>
+#include <Magnum/Math/Vector2.h>
+#include <nlohmann/json.hpp>
+
+namespace nlohmann {
+
+template<typename t>
+struct adl_serializer<Magnum::Math::Vector2<t>> final {
+ static void to_json(json& j, const Magnum::Math::Vector2<t>& x);
+ static void from_json(const json& j, Magnum::Math::Vector2<t>& x);
+};
+
+template<typename t>
+void adl_serializer<Magnum::Math::Vector2<t>>::to_json(json& j, const Magnum::Math::Vector2<t>& val)
+{
+ char buf[64];
+ snprintf(buf, sizeof(buf), "%d x %d", val[0], val[1]);
+ j = buf;
+}
+
+template<typename t>
+void adl_serializer<Magnum::Math::Vector2<t>>::from_json(const json& j, Magnum::Math::Vector2<t>& val)
+{
+ std::string str = j;
+ int x = 0, y = 0, n = 0;
+ int ret = std::sscanf(str.c_str(), "%d x %d%n", &x, &y, &n);
+ if (ret != 2 || (std::size_t)n != str.size())
+ {
+ std::string msg; msg.reserve(64 + str.size());
+ msg += "failed to parse string '";
+ msg += str;
+ msg += "' as Magnum::Vector2i";
+ throw std::invalid_argument(msg);
+ }
+ val = { x, y };
+}
+
+} // namespace nlohmann