summaryrefslogtreecommitdiffhomepage
path: root/serialize/json-helper.hpp
blob: 6be7f74cdcafd4d8c3af624629ab469b3180f013 (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
53
54
#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 Corrade::Utility::Error;
    std::ifstream s;
    s.exceptions(s.exceptions() | std::ios::failbit | std::ios::badbit);
    try {
        s.open(pathname, std::ios_base::in);
    } catch (const std::ios::failure& e) {
        Error{} << "failed to open" << pathname << "for reading:" << e.what();
        return {};
    }
    t ret;
    nlohmann::json j;
    s >> j;
    ret = j;
    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{} << "failed to open" << pathname << "for writing:" << e.what();
        return false;
    }
    s << j.dump(4);
    s << '\n';
    s.flush();
    return true;
}