summaryrefslogtreecommitdiffhomepage
path: root/serialize/json-helper.cpp
blob: 9c3b5034b26aeb5a636724dda459689c7a5fdf72 (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 = []<std::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(1, '\t') << '\n').flush();
}

} // namespace floormat