-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.cpp
More file actions
64 lines (50 loc) · 1.57 KB
/
config.cpp
File metadata and controls
64 lines (50 loc) · 1.57 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
#include "config.h"
#include <fstream>
#include <print>
#include <ranges>
Config::Config(const std::string &filename)
{
// std::println("Opening {}", filename);
std::ifstream ifile(filename);
std::string line;
if (!ifile)
{
std::println("Could not open config file: {}", filename);
return;
}
while (std::getline(ifile, line))
{
// There are at least two ways to do this...
// This way with std::views::split, and using std::ranges::find_first_of and then using the delimiter offset
// I still think it's perverse that std::views::split turns 'A1=B2' into [['A', '1'], ['B', '2']]
// and not ["A1", "B2"] where [] denotes a range.
auto parts = line | std::views::split('=');
auto it = parts.begin();
if (it != parts.end())
{
// std::string_view has a constructor that takes a range since C++23.
std::string_view key(*it++);
std::string_view value(*it);
// std::println(" Config: Setting {} = {}", key, value);
values_[std::string(key)] = value;
}
}
}
const std::string &Config::at(const std::string &key) const
{
// std::println("retrieving {}: '{}'", key, values_[key]);
return values_.at(key);
}
const std::string &Config::operator[](const std::string &key) const
{
static std::string emptyStr = "";
// std::println("retrieving {} via []: '{}'", key, values_[key]);
try
{
return values_.at(key);
}
catch (std::out_of_range &e)
{
return emptyStr;
}
}