2 #include <unordered_set>
10 namespace elaboradar {
20 ConfigValue(
const char* key,
const char* env,
const char* def=0)
21 : key(key), env(env), def(def) {}
25 ConfigValue config_layout[] = {
26 {
"file/first_level",
"FIRST_LEVEL_FILE" },
27 {
"file/vpr_heating",
"VPR_HEATING" },
31 std::string trim(
const std::string s)
33 if (s.empty())
return s;
36 size_t end = s.size() - 1;
37 while (start < end && isspace(s[start]))
39 while (end > start && isspace(s[end]))
42 if (start == end)
return string();
43 if (start == 0 && end == s.size() - 1)
return s;
44 return s.substr(start, end - start);
48 bool is_empty(
const std::string& line)
52 if (isspace(i))
continue;
53 if (i ==
'#')
return true;
61 void Config::set_defaults()
63 for (
auto v : config_layout)
66 values[v.key] = v.def;
70 void Config::read_env()
72 for (
auto v : config_layout)
75 const char* val = getenv(v.env);
76 if (val == NULL)
continue;
81 void Config::read_file(
const std::string& fname)
88 unordered_set<string> valid_keys;
89 for (
auto v : config_layout)
90 valid_keys.insert(v.key);
92 while (getline(in, line))
95 if (is_empty(line))
continue;
97 size_t pos = line.find(
'=');
98 if (pos == string::npos)
101 s << fname <<
":" << lineno <<
": unparsed line (not empty, a comment or key = value)";
102 throw runtime_error(s.str());
104 string key = trim(line.substr(0, pos));
105 string val = trim(line.substr(pos+1));
106 if (valid_keys.find(key) == valid_keys.end())
109 s << fname <<
":" << lineno <<
": unsupported key '" << key <<
"'";
110 throw runtime_error(s.str());
116 bool Config::has(
const std::string& key)
const
118 return values.find(key) != values.end();
121 std::string Config::get(
const std::string& key)
const
123 auto res = values.find(key);
124 if (res == values.end())
throw std::runtime_error(
"configuration key " + key +
" not found");
128 std::string Config::get(
const std::string& key,
const std::string& deflt)
const
130 auto res = values.find(key);
131 if (res == values.end())
return deflt;
135 int Config::get_int(
const std::string& key)
const
137 auto res = values.find(key);
138 if (res == values.end())
throw std::runtime_error(
"configuration key " + key +
" not found");
139 return stoi(res->second);
142 int Config::get_int(
const std::string& key,
int deflt)
const
144 auto res = values.find(key);
145 if (res == values.end())
return deflt;
146 return stoi(res->second);
149 double Config::get_double(
const std::string& key)
const
151 auto res = values.find(key);
152 if (res == values.end())
throw std::runtime_error(
"configuration key " + key +
" not found");
153 return stod(res->second);
156 double Config::get_double(
const std::string& key,
double deflt)
const
158 auto res = values.find(key);
159 if (res == values.end())
return deflt;
160 return stod(res->second);