blob: 345efe54875fec28b356fca3537b849388b2ab9e (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
#pragma once
#include <tuple>
#include <fstream>
#include <exception>
#include <filesystem>
#include <nlohmann/json.hpp>
#include <Corrade/Utility/DebugStl.h>
struct json_helper final {
template<typename t>
[[nodiscard]]
static std::tuple<t, bool> from_json(const std::filesystem::path& pathname);
template<typename t>
[[nodiscard]]
static bool to_json(const t& self, const std::filesystem::path& pathname);
};
template<typename t>
std::tuple<t, bool> json_helper::from_json(const std::filesystem::path& pathname) {
using namespace nlohmann;
using Corrade::Utility::Error;
std::ifstream s;
s.exceptions(s.exceptions() | std::ios::failbit | std::ios::badbit);
s.open(pathname, std::ios_base::in);
t ret;
json j;
s >> j;
using nlohmann::from_json;
from_json(j, ret);
return { std::move(ret), true };
}
template<typename t>
bool json_helper::to_json(const t& self, const std::filesystem::path& pathname) {
using Corrade::Utility::Error;
nlohmann::json j = self;
std::ofstream s;
s.exceptions(s.exceptions() | std::ios::failbit | std::ios::badbit);
try {
s.open(pathname, std::ios_base::out | std::ios_base::trunc);
} catch (const std::ios::failure& e) {
Error{Error::Flag::NoSpace} << "failed to open '" << pathname << "' for writing: " << e.what();
return false;
}
s << j.dump(4);
s << '\n';
s.flush();
return true;
}
|