aboutsummaryrefslogtreecommitdiff
path: root/src/base/PropertyTree.cpp
blob: ea47dabcbb26be62e222eb2702b2d9165ba7b999 (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
64
65
66
67
68
69
70
71
72
73
#include "cru/base/PropertyTree.h"
#include "cru/base/Exception.h"

namespace cru {
std::string PropertySubTreeRef::CombineKey(std::string_view left,
                                           std::string_view right) {
  return PropertyTree::CombineKey(left, right);
}

PropertySubTreeRef::PropertySubTreeRef(PropertyTree* tree, std::string path)
    : tree_(tree), path_(std::move(path)) {
  Expects(tree);
}

PropertySubTreeRef PropertySubTreeRef::GetParent() const {
  for (Index i = path_.size() - 1; i >= 0; i--) {
    if (path_[i] == '.') {
      return PropertySubTreeRef(tree_, path_.substr(0, i));
    }
  }

  return PropertySubTreeRef(tree_, {});
}

PropertySubTreeRef PropertySubTreeRef::GetChild(const std::string& key) const {
  return PropertySubTreeRef(tree_, CombineKey(path_, key));
}

std::string PropertySubTreeRef::GetValue(const std::string& key) const {
  return tree_->GetValue(CombineKey(path_, key));
}

void PropertySubTreeRef::SetValue(const std::string& key, std::string value) {
  tree_->SetValue(CombineKey(path_, key), std::move(value));
}

void PropertySubTreeRef::DeleteValue(const std::string& key) {
  tree_->DeleteValue(CombineKey(path_, key));
}

std::string PropertyTree::CombineKey(std::string_view left,
                                     std::string_view right) {
  return std::string(left) + std::string(left.empty() ? "" : ".") +
         std::string(right);
}

PropertyTree::PropertyTree(std::unordered_map<std::string, std::string> values)
    : values_(std::move(values)) {}

std::string PropertyTree::GetValue(const std::string& key) const {
  auto it = values_.find(key);
  if (it == values_.end()) {
    throw Exception("Property tree has no value.");
  }
  return it->second;
}

void PropertyTree::SetValue(const std::string& key, std::string value) {
  values_[key] = std::move(value);
}

void PropertyTree::DeleteValue(const std::string& key) {
  auto it = values_.find(key);
  if (it != values_.end()) {
    values_.erase(it);
  }
}

PropertySubTreeRef PropertyTree::GetSubTreeRef(const std::string& path) {
  return PropertySubTreeRef(this, path);
}

}  // namespace cru