Step 2
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
message(STATUS "··Configuring Common")
|
||||
|
||||
add_library(Config.Common
|
||||
IniParser.cpp
|
||||
)
|
||||
|
||||
add_library(Config::Common ALIAS Config.Common)
|
||||
|
||||
target_include_directories(Config.Common
|
||||
PUBLIC
|
||||
${INCLUDE_BASE_DIR}
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
#include "Config/Common/IniParser.h"
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <algorithm>
|
||||
|
||||
static std::string trim(std::string s)
|
||||
{
|
||||
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int c)
|
||||
{ return !isspace(c); }));
|
||||
s.erase(std::find_if(s.rbegin(), s.rend(), [](int c)
|
||||
{ return !isspace(c); })
|
||||
.base(),
|
||||
s.end());
|
||||
return s;
|
||||
}
|
||||
|
||||
bool IniParser::load(const std::string &path)
|
||||
{
|
||||
std::ifstream f(path);
|
||||
if (!f)
|
||||
return false;
|
||||
|
||||
std::string line, section;
|
||||
while (std::getline(f, line))
|
||||
{
|
||||
line = trim(line);
|
||||
if (line.empty() || line[0] == '#' || line[0] == ';')
|
||||
continue;
|
||||
|
||||
if (line.front() == '[' && line.back() == ']')
|
||||
{
|
||||
section = line.substr(1, line.size() - 2);
|
||||
continue;
|
||||
}
|
||||
|
||||
auto pos = line.find('=');
|
||||
if (pos == std::string::npos)
|
||||
continue;
|
||||
|
||||
std::string key = trim(line.substr(0, pos));
|
||||
std::string val = trim(line.substr(pos + 1));
|
||||
data_[section][key] = val;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string IniParser::get(const std::string §ion,
|
||||
const std::string &key,
|
||||
const std::string &def) const
|
||||
{
|
||||
auto s = data_.find(section);
|
||||
if (s == data_.end())
|
||||
return def;
|
||||
auto k = s->second.find(key);
|
||||
if (k == s->second.end())
|
||||
return def;
|
||||
return k->second;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
class IniParser
|
||||
{
|
||||
public:
|
||||
bool load(const std::string &path);
|
||||
|
||||
std::string get(const std::string §ion,
|
||||
const std::string &key,
|
||||
const std::string &def = "") const;
|
||||
|
||||
private:
|
||||
using Section = std::unordered_map<std::string, std::string>;
|
||||
std::unordered_map<std::string, Section> data_;
|
||||
};
|
||||
Reference in New Issue
Block a user