aboutsummaryrefslogtreecommitdiff
path: root/src/toml/TomlParser.cpp
blob: 7f19c71113a859f52efe153951301c93961c73f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "cru/toml/TomlParser.hpp"
#include "cru/toml/TomlDocument.hpp"

namespace cru::toml {
TomlParser::TomlParser(String input) : input_(std::move(input)) {}

TomlParser::~TomlParser() = default;

TomlDocument TomlParser::Parse() {
  if (cache_) {
    return *cache_;
  }

  cache_ = TomlDocument();
  DoParse(*cache_);
  return *cache_;
}

void TomlParser::DoParse(TomlDocument& document) {
  std::vector<String> lines = input_.SplitToLines(true);

  String current_section_name;

  for (auto& line : lines) {
    line.Trim();
    if (line.StartWith(u"[") && line.EndWith(u"]")) {
      current_section_name = line.substr(1, line.size() - 2);
    } else if (line.StartWith(u"#")) {
      // Ignore comments.
    } else {
      auto equal_index = line.Find(u'=');

      if (equal_index == -1) {
        throw TomlParsingException(u"Invalid TOML line: " + line);
      }

      auto key = line.substr(0, equal_index).Trim();
      auto value = line.substr(equal_index + 1).Trim();

      auto remove_quote = [](const String& str) -> String {
        if (str.size() < 2) {
          return str;
        }

        if (str.StartWith(u"\"") && str.EndWith(u"\"")) {
          return str.substr(1, str.size() - 2);
        }

        if (str.StartWith(u"\'") && str.EndWith(u"\'")) {
          return str.substr(1, str.size() - 2);
        }

        return str;
      };

      key = remove_quote(key);
      value = remove_quote(value);

      document.GetSectionOrCreate(current_section_name)->SetValue(key, value);
    }
  }
}
}  // namespace cru::toml