ConfigFileParser.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2015 Patrick Brosi
  2. // info@patrickbrosi.de
  3. #pragma once
  4. #include <exception>
  5. #include <fstream>
  6. #include <sstream>
  7. #include <string>
  8. #include <unordered_map>
  9. #include <vector>
  10. namespace configparser {
  11. struct Val {
  12. std::string val;
  13. size_t line;
  14. size_t pos;
  15. };
  16. typedef std::string Key;
  17. typedef std::string Sec;
  18. typedef std::unordered_map<std::string, Val> KeyVals;
  19. enum State {
  20. NONE,
  21. IN_HEAD,
  22. IN_HEAD_KEY,
  23. IN_HEAD_AW_COM_OR_END,
  24. IN_KEY_VAL_KEY,
  25. IN_KEY_VAL_VAL,
  26. AW_KEY_VAL_VAL,
  27. IN_KEY_VAL_VAL_HANG,
  28. IN_KEY_VAL_VAL_HANG_END
  29. };
  30. class ParseExc : public std::exception {
  31. public:
  32. ParseExc(size_t l, size_t p, std::string exc, std::string f, std::string file)
  33. : _l(l), _p(p), _exc(exc), _f(f), _file(file), _msg() {
  34. std::stringstream ss;
  35. ss << _file << ":" << _l << ", at pos " << _p << ": Expected " << _exc
  36. << ", found " << _f;
  37. _msg = ss.str();
  38. };
  39. virtual const char* what() const throw() { return _msg.c_str(); }
  40. private:
  41. size_t _l;
  42. size_t _p;
  43. std::string _exc, _f, _file, _msg;
  44. };
  45. class ConfigFileParser {
  46. public:
  47. ConfigFileParser();
  48. void parse(const std::string& path);
  49. const std::string& getStr(Sec sec, const Key& key) const;
  50. int getInt(Sec sec, const Key& key) const;
  51. double getDouble(Sec sec, const Key& key) const;
  52. bool getBool(Sec sec, const Key& key) const;
  53. std::vector<std::string> getStrArr(Sec sec, const Key& key, char del) const;
  54. std::vector<int> getIntArr(Sec sec, const Key& key, char del) const;
  55. std::vector<double> getDoubleArr(Sec sec, const Key& key, char del) const;
  56. std::vector<bool> getBoolArr(Sec sec, const Key& key, char del) const;
  57. std::string toString() const;
  58. const std::unordered_map<std::string, size_t> getSecs() const;
  59. bool hasKey(Sec section, Key key) const;
  60. const Val& getVal(Sec section, Key key) const;
  61. private:
  62. std::unordered_map<std::string, size_t> _secs;
  63. std::vector<KeyVals> _kvs;
  64. bool isKeyChar(char t) const;
  65. std::string trim(const std::string& str) const;
  66. bool toBool(std::string str) const;
  67. };
  68. }