-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.h
More file actions
429 lines (382 loc) · 13 KB
/
config.h
File metadata and controls
429 lines (382 loc) · 13 KB
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#pragma once
#include <cctype>
#include <fstream>
#include <map>
#include <limits>
#include <memory>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>
#include "ini.h"
namespace cpplib {
class ConfigSource {
public:
virtual ~ConfigSource() = default;
virtual bool reload() = 0;
virtual std::optional<Ini::Value> find(std::string_view section, std::string_view key) const = 0;
};
class IniConfigSource final : public ConfigSource {
public:
explicit IniConfigSource(std::string path) : path_(std::move(path)) {
reload();
}
bool reload() override {
Ini loaded;
if (!loaded.load(path_)) {
return false;
}
data_ = std::move(loaded);
return true;
}
std::optional<Ini::Value> find(std::string_view section, std::string_view key) const override {
return data_.try_get(std::string(section), std::string(key));
}
const Ini& data() const { return data_; }
private:
std::string path_;
Ini data_;
};
class JsonConfigSource;
class Config {
public:
void addSource(std::shared_ptr<ConfigSource> source) {
sources_.push_back(std::move(source));
}
void clearSources() {
sources_.clear();
}
bool reloadAll() {
bool ok = true;
for (auto& source : sources_) {
ok &= source->reload();
}
return ok;
}
template <typename T>
std::optional<T> get(std::string_view section, std::string_view key) const {
for (auto it = sources_.rbegin(); it != sources_.rend(); ++it) {
if (!(*it)) {
continue;
}
auto value = (*it)->find(section, key);
if (!value) {
continue;
}
if (auto converted = convert<T>(*value)) {
return converted;
}
}
return std::nullopt;
}
template <typename T>
T getOr(std::string_view section, std::string_view key, T fallback) const {
if (auto value = get<T>(section, key)) {
return *value;
}
return fallback;
}
private:
template <typename T>
static std::optional<T> convert(const Ini::Value& value) {
if (std::holds_alternative<T>(value)) {
return std::get<T>(value);
}
if constexpr (std::is_same_v<T, std::string>) {
return std::visit([](const auto& v) {
using V = std::decay_t<decltype(v)>;
if constexpr (std::is_same_v<V, bool>) {
return v ? std::string{"true"} : std::string{"false"};
} else if constexpr (std::is_same_v<V, std::string>) {
return v;
} else {
return std::to_string(v);
}
}, value);
} else if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
if (const auto* str = std::get_if<std::string>(&value)) {
T converted{};
std::istringstream iss(*str);
iss >> converted;
if (!iss.fail()) {
return converted;
}
}
if (const auto* dbl = std::get_if<double>(&value)) {
return static_cast<T>(*dbl);
}
if (const auto* integer = std::get_if<int>(&value)) {
return static_cast<T>(*integer);
}
} else if constexpr (std::is_floating_point_v<T>) {
if (const auto* str = std::get_if<std::string>(&value)) {
T converted{};
std::istringstream iss(*str);
iss >> converted;
if (!iss.fail()) {
return converted;
}
}
if (const auto* dbl = std::get_if<double>(&value)) {
return static_cast<T>(*dbl);
}
if (const auto* integer = std::get_if<int>(&value)) {
return static_cast<T>(*integer);
}
} else if constexpr (std::is_same_v<T, bool>) {
if (const auto* str = std::get_if<std::string>(&value)) {
std::string lowered;
lowered.reserve(str->size());
for (char ch : *str) {
lowered.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(ch))));
}
if (lowered == "true") {
return true;
}
if (lowered == "false") {
return false;
}
}
if (const auto* integer = std::get_if<int>(&value)) {
return *integer != 0;
}
}
return std::nullopt;
}
std::vector<std::shared_ptr<ConfigSource>> sources_;
};
namespace detail {
class JsonParser {
public:
explicit JsonParser(std::string text) : text_(std::move(text)) {}
std::map<std::string, std::map<std::string, Ini::Value>> parse();
private:
char peek() const;
bool eof() const;
char get();
void skipWhitespace();
bool consume(char expected);
void expect(char expected);
std::string parseString();
Ini::Value parseNumber();
Ini::Value parseLiteral();
std::map<std::string, Ini::Value> parseSectionObject();
std::string text_;
std::size_t pos_ = 0;
};
}
class JsonConfigSource final : public ConfigSource {
public:
explicit JsonConfigSource(std::string path) : path_(std::move(path)) {
reload();
}
bool reload() override {
std::ifstream file(path_);
if (!file.is_open()) {
return false;
}
std::ostringstream oss;
oss << file.rdbuf();
detail::JsonParser parser(oss.str());
auto sections = parser.parse();
Ini loaded;
for (auto& [section, entries] : sections) {
for (auto& [key, value] : entries) {
loaded.set(section, key, value);
}
}
data_ = std::move(loaded);
return true;
}
std::optional<Ini::Value> find(std::string_view section, std::string_view key) const override {
return data_.try_get(std::string(section), std::string(key));
}
const Ini& data() const { return data_; }
private:
std::string path_;
Ini data_;
};
inline std::map<std::string, std::map<std::string, Ini::Value>> detail::JsonParser::parse() {
skipWhitespace();
expect('{');
skipWhitespace();
std::map<std::string, std::map<std::string, Ini::Value>> result;
bool first = true;
while (!consume('}')) {
if (!first) {
expect(',');
skipWhitespace();
}
first = false;
skipWhitespace();
auto section = parseString();
skipWhitespace();
expect(':');
skipWhitespace();
result.emplace(section, parseSectionObject());
skipWhitespace();
}
return result;
}
inline char detail::JsonParser::peek() const {
if (eof()) {
return '\0';
}
return text_[pos_];
}
inline bool detail::JsonParser::eof() const {
return pos_ >= text_.size();
}
inline char detail::JsonParser::get() {
if (eof()) {
throw std::runtime_error("Unexpected end of JSON input");
}
return text_[pos_++];
}
inline void detail::JsonParser::skipWhitespace() {
while (!eof() && std::isspace(static_cast<unsigned char>(text_[pos_]))) {
++pos_;
}
}
inline bool detail::JsonParser::consume(char expected) {
if (!eof() && text_[pos_] == expected) {
++pos_;
return true;
}
return false;
}
inline void detail::JsonParser::expect(char expected) {
if (!consume(expected)) {
std::ostringstream oss;
oss << "Expected '" << expected << "'";
throw std::runtime_error(oss.str());
}
}
inline std::string detail::JsonParser::parseString() {
expect('"');
std::string result;
while (true) {
if (eof()) {
throw std::runtime_error("Unterminated string literal");
}
char ch = get();
if (ch == '"') {
break;
}
if (ch == '\\') {
if (eof()) {
throw std::runtime_error("Invalid escape sequence");
}
char escaped = get();
switch (escaped) {
case '"': result.push_back('"'); break;
case '\\': result.push_back('\\'); break;
case '/': result.push_back('/'); break;
case 'b': result.push_back('\b'); break;
case 'f': result.push_back('\f'); break;
case 'n': result.push_back('\n'); break;
case 'r': result.push_back('\r'); break;
case 't': result.push_back('\t'); break;
default:
throw std::runtime_error("Unsupported escape sequence");
}
} else {
result.push_back(ch);
}
}
return result;
}
inline Ini::Value detail::JsonParser::parseNumber() {
std::size_t start = pos_;
if (peek() == '-') {
++pos_;
}
while (std::isdigit(static_cast<unsigned char>(peek()))) {
++pos_;
}
bool is_float = false;
if (peek() == '.') {
is_float = true;
++pos_;
while (std::isdigit(static_cast<unsigned char>(peek()))) {
++pos_;
}
}
if (peek() == 'e' || peek() == 'E') {
is_float = true;
++pos_;
if (peek() == '+' || peek() == '-') {
++pos_;
}
while (std::isdigit(static_cast<unsigned char>(peek()))) {
++pos_;
}
}
auto number = text_.substr(start, pos_ - start);
try {
if (is_float) {
return std::stod(number);
}
long long value = std::stoll(number, nullptr, 10);
if (value > std::numeric_limits<int>::max()) {
return static_cast<double>(value);
}
if (value < std::numeric_limits<int>::min()) {
return static_cast<double>(value);
}
return static_cast<int>(value);
} catch (...) {
throw std::runtime_error("Invalid numeric literal");
}
}
inline Ini::Value detail::JsonParser::parseLiteral() {
if (text_.compare(pos_, 4, "true") == 0) {
pos_ += 4;
return true;
}
if (text_.compare(pos_, 5, "false") == 0) {
pos_ += 5;
return false;
}
if (text_.compare(pos_, 4, "null") == 0) {
pos_ += 4;
return std::string{};
}
throw std::runtime_error("Invalid literal value");
}
inline std::map<std::string, Ini::Value> detail::JsonParser::parseSectionObject() {
skipWhitespace();
expect('{');
skipWhitespace();
std::map<std::string, Ini::Value> entries;
bool first = true;
while (!consume('}')) {
if (!first) {
expect(',');
skipWhitespace();
}
first = false;
auto key = parseString();
skipWhitespace();
expect(':');
skipWhitespace();
Ini::Value value;
char ch = peek();
if (ch == '"') {
value = parseString();
} else if (ch == '{') {
throw std::runtime_error("Nested objects beyond two levels are not supported");
} else if (std::isdigit(static_cast<unsigned char>(ch)) || ch == '-' ) {
value = parseNumber();
} else {
value = parseLiteral();
}
entries.emplace(std::move(key), std::move(value));
skipWhitespace();
}
return entries;
}
}