summaryrefslogtreecommitdiffhomepage
path: root/serialize/json-helper.cpp
diff options
context:
space:
mode:
authorStanislaw Halik <sthalik@misaki.pl>2022-10-27 14:11:54 +0200
committerStanislaw Halik <sthalik@misaki.pl>2022-10-27 14:11:54 +0200
commit0c468a802bd6c41bf57bd674cb9f44157a3af155 (patch)
tree6505c1522040df4880e4ca64b2613b7e8bd23c72 /serialize/json-helper.cpp
parent06f7a92711c114df01745d40accba15b10d2f720 (diff)
serialize: slim down json-helper header
Diffstat (limited to 'serialize/json-helper.cpp')
-rw-r--r--serialize/json-helper.cpp47
1 files changed, 47 insertions, 0 deletions
diff --git a/serialize/json-helper.cpp b/serialize/json-helper.cpp
new file mode 100644
index 00000000..8738065f
--- /dev/null
+++ b/serialize/json-helper.cpp
@@ -0,0 +1,47 @@
+#include "json-helper.hpp"
+#include <fstream>
+#include <filesystem>
+
+namespace floormat {
+
+template<typename T, typename P, std::ios_base::openmode open_mode>
+static T open_stream(const std::remove_cvref_t<P>& filename)
+{
+ T s;
+ s.exceptions(s.exceptions() | std::ios::failbit | std::ios::badbit);
+ s.open(filename, open_mode);
+ return s;
+}
+
+auto json_helper::from_json_(const fspath& pathname) -> json
+{
+ json j;
+ open_stream<std::ifstream, fspath, std::ios_base::in>(pathname) >> j;
+ return j;
+}
+
+void json_helper::to_json_(const json& j, const fspath& pathname, int indent)
+{
+ (open_stream<std::ofstream, fspath, std::ios_base::out>(pathname) << j.dump(indent, '\t') << '\n').flush();
+}
+
+#define FORMAT cbor
+
+#define JOIN2(prefix, fmt) prefix ## fmt
+#define JOIN(prefix, fmt) JOIN2(prefix, fmt)
+#define FROM JOIN(from_, FORMAT)
+#define TO JOIN(to_, FORMAT)
+
+auto json_helper::from_binary_(const fspath& pathname) -> json
+{
+ return json::FROM(open_stream<std::ifstream, fspath, std::ios_base::in>(pathname));
+}
+
+void json_helper::to_binary_(const json& j, const fspath& pathname)
+{
+ auto s = open_stream<std::ofstream, fspath, std::ios_base::out>(pathname);
+ json::TO(j, s);
+ s.flush();
+}
+
+} // namespace floormat