Utilities
Utilities header only library
IniParser.h
1 /*
2  Copyright (C) Skeletex Research, s.r.o. - All Rights Reserved
3  Unauthorized copying of this file, via any medium is strictly prohibited
4  Proprietary and confidential
5 */
6 #ifndef UTILS_INI_PARSER_H
7 #define UTILS_INI_PARSER_H
8 #include <fstream>
9 #include <Utils/ExtSTD.h>
10 #include <Utils/ExtGLM.h>
11 #include <Utils/Dictionary.h>
12 #include <Utils/Ulog.h>
13 
14 namespace utils
15 {
16 
17  class IniParser
18  {
19  public:
20 
21  IniParser() = default;
22 
23  IniParser(const std::string &filename)
24  {
25  LoadFile(filename);
26  };
27 
29  std::string PopErrorLog()
30  {
31  auto log = error_log_;
32  error_log_.clear();
33  return log;
34  }
35 
37  const std::unordered_set<std::string> &GetUnreadableRecords() const
38  {
39  return unreadable_records_;
40  }
41 
43  bool LoadFile(const std::string &file_name)
44  {
45  std::ifstream ifs(file_name);
46 
47  if (!ifs.is_open())
48  {
49  ulog::Fail("Config file \"" + file_name + "\" was not found.");
50  return false;
51  }
52 
53  std::string line;
54  std::string section;
55  while (std::getline(ifs, line))
56  {
57  std_ext::Trim(line);
58  if (line.empty() || line[0] == '#')
59  {
60  continue;
61  }
62  if (line.front() == '[' && line.back() == ']')
63  {
64  section = line.substr(1, line.length() - 2);
65  continue;
66  }
67  Record record = GetRecord(line);
68  if (!record.first.empty())
69  {
70  if (!std_ext::IsASCII(record.first) || !std_ext::IsASCII(record.second))
71  {
72  unreadable_records_.emplace(record.first + " : " + record.second);
73  continue;
74  }
75 
76  if (!section.empty())
77  {
78  record.first = section + "/" + record.first;
79  }
80  dictionary_.Set(record.first.c_str(), record.second.c_str());
81  }
82  }
83 
84  return true;
85  }
86 
88  void Clear()
89  {
90  error_log_.clear();
91  dictionary_.Clear();
92  }
93 
95  bool Exists(const std::string &key) const
96  {
97  return dictionary_.IsAvailable(key.c_str());
98  }
99 
101  std::string GetStr(const std::string &key, const std::string &default_val = "") const
102  {
103  if (!Exists(key))
104  {
105  LogStandardError(key, "'" + default_val + "'");
106  return default_val;
107  }
108  return dictionary_.Get(key.c_str());
109  }
110 
112  bool GetBool(const std::string &key, const bool default_val = false) const
113  {
114  if (!Exists(key))
115  {
116  LogStandardError(key, std_ext::BoolToString(default_val));
117  return default_val;
118  }
119  const std::string val = dictionary_.Get(key.c_str());
120  return !(val == "0" || std_ext::Lowercase(val) == "false");
121  }
122 
124  size_t GetSizeT(const std::string &key, const size_t default_val = 0) const
125  {
126  return static_cast<size_t>(GetInt(key, static_cast<int>(default_val)));
127  }
128 
130  template<typename Type>
131  Type GetUint(const std::string &key, const Type default_val = 0) const
132  {
133  return static_cast<Type>(GetInt(key, static_cast<int>(default_val)));
134  }
135 
137  int GetInt(const std::string &key, const int default_val = 0) const
138  {
139  if (!Exists(key))
140  {
141  LogStandardError(key, std::to_string(default_val));
142  return default_val;
143  }
144  return std::stoi(dictionary_.Get(key.c_str()));
145  }
146 
148  float GetFloat(const std::string &key, const float default_val = 0.0f) const
149  {
150  if (!Exists(key))
151  {
152  LogStandardError(key, std::to_string(default_val));
153  return default_val;
154  }
155  return std::stof(dictionary_.Get(key.c_str()));
156  }
157 
159  double GetDouble(const std::string &key, const double default_val = 0.0) const
160  {
161  if (!Exists(key))
162  {
163  LogStandardError(key, std::to_string(default_val));
164  return default_val;
165  }
166  return std::stod(dictionary_.Get(key.c_str()));
167  }
168 
170  template <glm::length_t N, typename Type>
171  glm::vec<N, Type, glm::highp> GetVec(const std::string &key, const glm::vec<N, Type, glm::highp> default_val = glm::vec<N, Type, glm::highp>(0))
172  {
173  if (!Exists(key))
174  {
175  LogStandardError(key, "(" + glm_ext::to_string(default_val, ",") + ")");
176  return default_val;
177  }
178  auto elements = std_ext::Parse(dictionary_.Get(key.c_str()), " ");
179  if (elements.size() != N)
180  {
181  auto el0 = std::to_string(N);
182  auto el1 = std::to_string(elements.size());
183  error_log_ += "[" + key + "] key contains invalid value.";
184  error_log_ += "Expected vector of " + el0 + " elements, not " + el1 + ".";
185  error_log_ += "Using (" + glm_ext::to_string(default_val, ", ") + ")\n";
186  return default_val;
187  }
188  glm::vec<N, Type, glm::highp> result;
189  for (glm::length_t i = 0; i < N; ++i)
190  {
191  result[i] = Type(std::stod(elements[i]));
192  }
193  return result;
194  }
195 
197  std::vector<float> GetFloatArray(const std::string &key, const std::vector<float> &default_val = {}) const
198  {
199  const auto result = std_ext::Transformed(GetArray(key), [this, key](std::string number_as_string)
200  {
201  return std::stof(number_as_string);
202  });
203 
204  return result.empty() ? default_val : result;
205  }
206 
208  std::vector<int> GetIntArray(const std::string &key, const std::vector<int> &default_val = {}) const
209  {
210  const auto result = std_ext::Transformed(GetArray(key), [this, key](std::string number_as_string)
211  {
212  return std::stoi(number_as_string);
213  });
214 
215  return result.empty() ? default_val : result;
216  }
217 
219  std::vector<bool> GetBoolArray(const std::string &key, const std::vector<bool> &default_val = {}) const
220  {
221  const auto result = std_ext::Transformed(GetArray(key), [this, key](std::string number_as_string)
222  {
223  return !(number_as_string == "0" || std_ext::Lowercase(number_as_string) == "false");
224  });
225 
226  return result.empty() ? default_val : result;
227  }
228 
230  std::vector<std::string> GetArray(const std::string &key, const std::vector<std::string> &default_val = {}) const
231  {
232  std::string next_arr_key = key + "[0]";
233  std::vector<std::string> result;
234  if (!Exists(next_arr_key))
235  {
236  LogStandardError(next_arr_key, "empty array");
237  return default_val;
238  }
239  uint32_t next_i = 1;
240  while (Exists(next_arr_key))
241  {
242  result.emplace_back(dictionary_.Get(next_arr_key.c_str()));
243  next_arr_key = key + "[" + std::to_string(next_i) + "]";
244  ++next_i;
245  }
246  return result;
247  }
248 
249  protected:
250  std::map<std::string, std::string> replacement_map_;
251  const bool is_replacement_map_enabled_ = false;
252  utils::Dictionary dictionary_;
253  mutable std::string error_log_;
254  mutable std::unordered_set<std::string> unreadable_records_;
255 
256  void LogStandardError(const std::string &key, const std::string &val) const
257  {
258  error_log_ += "[" + key + "] key not found, using " + val + ".\n\r";
259  }
260 
261  using Record = std::pair<std::string, std::string>;
262 
263  virtual Record GetRecord(const std::string &line)
264  {
265  Record record;
266  size_t delim_pos = line.find_first_of("=");
267  if (delim_pos == std::string::npos)
268  {
269  record = Record(line, "0");
270  }
271  else
272  {
273  record.first = line.substr(0, delim_pos);
274  record.second = line.substr(delim_pos + 1, line.size());
275  }
276  std_ext::Trim(record.first);
277  std_ext::Trim(record.second);
278 
279  if (record.second.size() >= 2 && record.second.front() == '"' && record.second.back() == '"')
280  {
281  record.second = record.second.substr(1, record.second.length() - 2);
282  }
283 
284  if (is_replacement_map_enabled_)
285  {
286  record.second = std_ext::Replace(record.second, replacement_map_);
287  }
288 
289  return record;
290  }
291 
292  };
293 
294 }
295 #endif /* !UTILS_INI_PARSER_H */
std::string Lowercase(const std::string &text)
Converts text into all lowercase.
Definition: ExtSTD.h:311
std::string to_string(const glm::vec< N, genType, glm::highp > &vec, const std::string &delim=", ")
Converts the input vector into a string with predefined delimiter.
Definition: ExtGLM.h:87
std::string & Trim(std::string &s, const std::string &t=WHITESPACES)
Trims from both ends of string (left & right).
Definition: ExtSTD.h:719
bool IsASCII(const std::string &s)
Check std::string for non-ASCII characters.
Definition: ExtSTD.h:1011
Type
Enum class that specifies (geometry) file types that we recognize.
Definition: FileTypes.h:33
std::vector< std::string > Parse(const std::string &text, const std::string &separators=WHITESPACES)
Parses the input text to sub strings by a given list of separators.
Definition: ExtSTD.h:735
auto Transformed(const C &container, F Function)
Simplified wrapper for std::transform.
Definition: ExtSTD.h:831
Enables mapping string keys to string words efficiently.
Definition: Dictionary.h:19
General namespace for utilities.
Definition: BulletConversions.h:9
std::string BoolToString(const bool value)
Converts bool to string ("true" or "false").
Definition: ExtSTD.h:160
std::string Replace(const std::string &text, const std::string &key_to_search, const std::string &replace_text)
Replaces all occurrences of key_to_search with replace_text in specified text.
Definition: ExtSTD.h:117