summaryrefslogtreecommitdiffhomepage
path: root/serialize/json-helper.cpp
blob: 695b76ef78bed3391f930cf8170bbbcce03e4776 (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
#include "json-helper.hpp"
#include "compat/exception.hpp"
#include <cerrno>
#include <cstring>
#include <fstream>
#include <Corrade/Containers/StringStlView.h>

namespace floormat {

template<typename T, std::ios_base::openmode mode>
static T open_stream(StringView filename)
{
    T s;
    s.exceptions(std::ios_base::failbit | std::ios_base::badbit);
    s.open(filename.data(), mode);
    if (!s)
    {
        char errbuf[128];
        constexpr auto get_error_string = []<size_t N> (char (&buf)[N])
        {
            buf[0] = '\0';
#ifndef _WIN32
            (void)::strerror_r(errno, buf, std::size(buf));
#else
            (void)::strerror_s(buf, std::size(buf), errno);
#endif
        };
        const char* mode_str = (mode & std::ios_base::out) == std::ios_base::out ? "writing" : "reading";
        (void)get_error_string(errbuf);
        fm_throw("can't open file '{}' for {}: {}"_cf, filename, mode_str, errbuf);
    }
    return s;
}

auto json_helper::from_json_(StringView filename) noexcept(false) -> json
{
    json j;
    open_stream<std::ifstream, std::ios_base::in>(filename) >> j;
    return j;
}

void json_helper::to_json_(const json& j, StringView filename) noexcept(false)
{
    (open_stream<std::ofstream, std::ios_base::out>(filename) << j.dump(2, ' ') << '\n').flush();
}

} // namespace floormat