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
77
78
79
80
81
82
#include "fsCloudSaveServiceLocalFolder.h"

#include <fsCore/src/fsSavedFile.h>

#include <fstream>
#include <iterator>
#include <system_error>

void fsCloudSaveServiceLocalFolder::initialize(const fsCloudSaveConfig& config)
{
    if (!config.providerName.empty())
    {
        mProviderName = config.providerName;
    }
    mFolder = std::filesystem::u8path(config.localFolderPath);

    std::error_code error;
    std::filesystem::create_directories(mFolder, error);
}

const std::string& fsCloudSaveServiceLocalFolder::providerNameGet() const
{
    return mProviderName;
}

bool fsCloudSaveServiceLocalFolder::availableGet() const
{
    std::error_code error;
    return !mFolder.empty() && std::filesystem::is_directory(mFolder, error);
}

void fsCloudSaveServiceLocalFolder::read(const std::string& name, ReadCallback done)
{
    const std::filesystem::path path = mFolder / std::filesystem::u8path(name);
    mPending.push_back([path, done]()
    {
        std::ifstream file(path, std::ios::binary);
        if (!file)
        {
            done(fsCloudSaveResult::eNOT_FOUND, std::string());
            return;
        }
        const std::string data{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
        done(fsCloudSaveResult::eOK, data);
    });
}

void fsCloudSaveServiceLocalFolder::write(const std::string& name, const std::string& data, DoneCallback done)
{
    const std::filesystem::path path = mFolder / std::filesystem::u8path(name);
    mPending.push_back([path, data, done]()
    {
        done(fsSavedFile::save(path, data) ? fsCloudSaveResult::eOK : fsCloudSaveResult::eERROR);
    });
}

void fsCloudSaveServiceLocalFolder::remove(const std::string& name, DoneCallback done)
{
    const std::filesystem::path path = mFolder / std::filesystem::u8path(name);
    mPending.push_back([path, done]()
    {
        std::error_code error;
        const bool removed = std::filesystem::remove(path, error);
        done(error ? fsCloudSaveResult::eERROR : (removed ? fsCloudSaveResult::eOK : fsCloudSaveResult::eNOT_FOUND));
    });
}

void fsCloudSaveServiceLocalFolder::update()
{
    // Callbacks may queue more work; that runs on the next update.
    std::vector<std::function<void()>> pending;
    pending.swap(mPending);
    for (auto& call : pending)<--- Variable 'call' can be declared as reference to const
    {
        call();
    }
}

void fsCloudSaveServiceLocalFolder::shutdown()
{
    update();
}