summaryrefslogtreecommitdiffstats
path: root/src/core/io/physfs.cc
blob: b9fe91e3020d3a78edb9c29b9e2e1d399e729b64 (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
69
70
71
72
73
74
75
76
#include "core/pch.hh"

#include "core/io/physfs.hh"

bool read_file(std::string_view path, std::vector<std::byte>& buffer)
{
    auto file = PHYSFS_openRead(std::string(path).c_str());

    if(file == nullptr) {
        spdlog::error("physfs: {}: {}", path, physfs_error());
        return false;
    }

    PHYSFS_sint64 file_size = PHYSFS_fileLength(file);
    buffer.resize(static_cast<std::size_t>(file_size));

    PHYSFS_readBytes(file, buffer.data(), file_size);
    PHYSFS_close(file);

    return true;
}

bool read_file(std::string_view path, std::string& buffer)
{
    auto file = PHYSFS_openRead(std::string(path).c_str());

    if(file == nullptr) {
        spdlog::error("physfs: {}: {}", path, physfs_error());
        return false;
    }

    PHYSFS_sint64 file_size = PHYSFS_fileLength(file);
    buffer.resize(static_cast<std::size_t>(file_size));

    PHYSFS_readBytes(file, buffer.data(), file_size);
    PHYSFS_close(file);

    return true;
}

bool write_file(std::string_view path, const std::vector<std::byte>& buffer)
{
    auto file = PHYSFS_openWrite(std::string(path).c_str());

    if(file == nullptr) {
        spdlog::error("physfs: {}: {}", path, physfs_error());
        return false;
    }

    PHYSFS_writeBytes(file, buffer.data(), static_cast<PHYSFS_uint64>(buffer.size()));
    PHYSFS_close(file);

    return true;
}

bool write_file(std::string_view path, const std::string& buffer)
{
    auto file = PHYSFS_openWrite(std::string(path).c_str());

    if(file == nullptr) {
        spdlog::error("physfs: {}: {}", path, physfs_error());
        return false;
    }

    PHYSFS_writeBytes(file, buffer.data(), static_cast<PHYSFS_uint64>(buffer.size()));
    PHYSFS_close(file);

    return true;
}

std::string_view physfs_error(void)
{
    auto error_code = PHYSFS_getLastErrorCode();
    auto error_string = PHYSFS_getErrorByCode(error_code);
    return std::string_view(error_string, std::strlen(error_string));
}