forked from organicmaps/organicmaps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_storage_base.cpp
124 lines (104 loc) · 2.55 KB
/
string_storage_base.cpp
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include "string_storage_base.hpp"
#include "coding/reader_streambuf.hpp"
#include "coding/file_reader.hpp"
#include "coding/file_writer.hpp"
#include "base/exception.hpp"
#include "base/logging.hpp"
#include "base/stl_helpers.hpp"
#include <istream>
namespace platform
{
namespace
{
constexpr char kKeyValueDelimChar = '=';
} // namespace
StringStorageBase::StringStorageBase(std::string const & path) : m_path(path)
{
try
{
LOG(LINFO, ("Settings path:", m_path));
ReaderStreamBuf buffer(std::make_unique<FileReader>(m_path));
std::istream stream(&buffer);
std::string line;
while (getline(stream, line))
{
if (line.empty())
continue;
size_t const delimPos = line.find(kKeyValueDelimChar);
if (delimPos == std::string::npos)
continue;
std::string const key = line.substr(0, delimPos);
std::string const value = line.substr(delimPos + 1);
if (!key.empty() && !value.empty())
m_values[key] = value;
}
}
catch (RootException const & ex)
{
LOG(LWARNING, ("Loading settings:", ex.Msg()));
}
}
void StringStorageBase::Save() const
{
try
{
FileWriter file(m_path);
for (auto const & value : m_values)
{
std::string line(value.first);
line += kKeyValueDelimChar;
line += value.second;
line += '\n';
file.Write(line.data(), line.size());
}
}
catch (RootException const & ex)
{
// Ignore all settings saving exceptions.
LOG(LWARNING, ("Saving settings:", ex.Msg()));
}
}
void StringStorageBase::Clear()
{
std::lock_guard guard(m_mutex);
m_values.clear();
Save();
}
bool StringStorageBase::GetValue(std::string const & key, std::string & outValue) const
{
std::lock_guard guard(m_mutex);
auto const found = m_values.find(key);
if (found == m_values.end())
return false;
outValue = found->second;
return true;
}
void StringStorageBase::SetValue(std::string const & key, std::string && value)
{
std::lock_guard guard(m_mutex);
m_values[key] = std::move(value);
Save();
}
void StringStorageBase::Update(std::map<std::string, std::string> const & values)
{
std::lock_guard guard(m_mutex);
for (const auto & pair : values)
{
if (pair.second.empty())
m_values.erase(pair.first);
else
m_values[pair.first] = pair.second;
}
Save();
}
void StringStorageBase::DeleteKeyAndValue(std::string const & key)
{
std::lock_guard guard(m_mutex);
auto const found = m_values.find(key);
if (found != m_values.end())
{
m_values.erase(found);
Save();
}
}
} // namespace platform