aboutsummaryrefslogtreecommitdiff
path: root/src/shared/shared.cc
blob: f5a478b6409f6d5e6cbb0e38dd30ce801ab3cb33 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "shared.hh"

namespace shared {

float get_duration_seconds(const time_duration_t& duration) noexcept {
    const auto fdiff =
        std::chrono::duration_cast<std::chrono::duration<float>>(duration);
    return fdiff.count();
}

std::string make_string_lower(std::string str) noexcept {
    std::ranges::transform(str.begin(), str.end(), str.begin(),
                           [](const auto c) { return std::tolower(c); });
    return str;
}

std::string read_file(const std::string& path) {
    std::ifstream input(path);
    if (!input.is_open()) {
        throw std::runtime_error("failed to read file: " + path);
    }
    return std::string{std::istreambuf_iterator<char>(input),
                       std::istreambuf_iterator<char>()};
}

std::ofstream open_file(const std::string& dir,
                        const std::ios_base::openmode mode) {
    std::ofstream ret(dir, mode);
    if (!ret.is_open()) {
        throw std::runtime_error("failed to write file: " + dir);
    }
    return ret;
}

std::string compress_string(const std::string& str) {
    std::stringstream input(str);

    boost::iostreams::filtering_streambuf<boost::iostreams::input> out;
    out.push(boost::iostreams::gzip_compressor(boost::iostreams::gzip_params(
        boost::iostreams::gzip::best_compression)));
    out.push(input);

    std::stringstream result;
    boost::iostreams::copy(out, result);

    return result.str();
}

std::optional<std::string>
maybe_decompress_string(const std::string& str) noexcept {
    try {
        std::stringstream input;
        input << str;

        boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
        in.push(boost::iostreams::gzip_decompressor());
        in.push(input);

        std::stringstream result;
        boost::iostreams::copy(in, result);

        return result.str();
    } catch (...) {
        return std::nullopt;
    }
}

} // namespace shared