Files
stvpn/works/config/config.cpp
T
2026-05-15 15:30:29 +02:00

127 lines
3.8 KiB
C++

#include <expected>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
std::vector<std::string> split(std::string s, std::string delimiters) {
std::vector<std::string> tokens;
size_t last = 0, next = 0;
while ((next = s.find_first_of(delimiters, last)) != std::string::npos) {
if (next != last) tokens.push_back(s.substr(last, next - last));
last = next + 1;
}
if (last < s.length()) tokens.push_back(s.substr(last));
return tokens;
}
std::string trim(std::string& source) {
auto line = source;
std::string whitespaces(" \t\n\r\f\v");
line.erase(0, line.find_first_not_of(whitespaces));
line.erase(line.find_last_not_of(whitespaces) + 1);
return line;
}
std::expected<int, std::string> str2int (std::string source) {
std::size_t pos{};
int res;
try {
res = std::stoi(source, &pos);
}
catch (std::invalid_argument const& ex) {
return std::unexpected(std::format("invalid argument:{}", ex.what()));
}
catch (std::out_of_range const& ex) {
return std::unexpected(std::format("out of range", ex.what()));
}
return res;
}
class Registry {
private:
std::map<std::string, std::string> kvmap;
std::vector<std::string> localnets;
std::string tunnelnet;
int listenport;
public:
std::expected<void, std::string> Read(std::string filename);
int Listenport(void);
std::string Tunnelnet(void);
std::vector<std::string> Localnets(void);
};
int Registry::Listenport(void){
return listenport;
}
std::vector<std::string> Registry::Localnets(void){
return localnets;
}
std::string Registry::Tunnelnet(void){
return tunnelnet;
}
std::expected<void, std::string> Registry::Read(std::string filename) {
std::ifstream file;
file.open(filename);
if (file.fail()) {
auto state = file.rdstate();
if (state & std::ios_base::badbit) {
return std::unexpected("Read/writing error on i/o operation");
} else if (state & std::ios_base::failbit) {
return std::unexpected("Logical error on i/o operation");
}
}
std::string line;
while (std::getline(file, line)) {
auto tokens = split(line, "#;");
auto keyval = trim(tokens[0]);
if (keyval.size() == 0) continue;
tokens = split(keyval, "=");
if (tokens.size() < 2) continue;
auto key = trim(tokens[0]);
auto val = trim(tokens[1]);
kvmap[key] = val;
if (key == "localnet") {
localnets.push_back(val);
} else if (key == "tunnelnet") {
tunnelnet = val;
} else if (key == "listenport") {
auto convRes = str2int(val);
if (!convRes) {
auto msg = std::format("listenport: {}", convRes.error());
return std::unexpected(msg);
}
listenport = convRes.value();
}
}
file.close();
//for (auto const& [key, val] : kvmap) {
// std::cout << key << ":" << val << std::endl;
//}
return {};
}
int main() {
Registry config;
auto openRes = config.Read("example.conf");
if (!openRes) {
std::cerr << openRes.error() << std::endl;
return 1;
}
return 0;
}