tree-gen
C++ code generator for tree structures
tree-annotatable.cpp.inc
Go to the documentation of this file.
1 #include <unordered_map>
2 
3 TREE_NAMESPACE_BEGIN
4 namespace annotatable {
5 
9 Anything::Anything(void *data, std::function<void(void *data)> destructor, std::type_index type) :
10  data(data),
11  destructor(destructor),
12  type(type)
13 {}
14 
18 Anything::Anything() :
19  data(nullptr),
20  destructor([](void*){}),
21  type(std::type_index(typeid(nullptr)))
22 {}
23 
27 Anything::~Anything() {
28  if (data) {
29  destructor(data);
30  }
31 }
32 
36 Anything::Anything(Anything &&src) :
37  data(src.data),
38  destructor(std::move(src.destructor)),
39  type(std::move(src.type))
40 {
41  src.data = nullptr;
42 }
43 
47 Anything& Anything::operator=(Anything &&src) {
48  if (data) {
49  destructor(data);
50  }
51  data = src.data;
52  destructor = std::move(src.destructor);
53  type = std::move(src.type);
54  src.data = nullptr;
55  return *this;
56 }
57 
61 std::type_index Anything::get_type_index() const {
62  return type;
63 };
64 
70 void SerDesRegistry::serialize(std::shared_ptr<Anything> obj, cbor::MapWriter &map) const {
71  if (!obj) return;
72  auto it = serializers.find(obj->get_type_index());
73  if (it != serializers.end()) {
74  it->second(obj, map);
75  }
76 }
77 
83 std::shared_ptr<Anything> SerDesRegistry::deserialize(const std::string &key, const cbor::Reader &value) const {
84  auto it = deserializers.find(key);
85  if (it != deserializers.end()) {
86  return it->second(value.as_map());
87  } else {
88  return nullptr;
89  }
90 }
91 
96 SerDesRegistry serdes_registry = SerDesRegistry();
97 
102 Annotatable::~Annotatable() {
103 };
104 
110 void Annotatable::copy_annotations(const Annotatable &src) {
111  for (const auto &src_it : src.annotations) {
112  TREE_MAP_SET(annotations, src_it.first, src_it.second);
113  }
114 }
115 
124 void Annotatable::serialize_annotations(cbor::MapWriter &map) const {
125  for (auto it : annotations) {
126  serdes_registry.serialize(it.second, map);
127  }
128 }
129 
139 void Annotatable::deserialize_annotations(const cbor::MapReader &map) {
140  for (auto it : map) {
141  // All annotation keys start with an { and close with a }. We
142  // immediately ignore any other keys.
143  if (!it.first.empty() && (it.first[0] == '{') && (it.first[it.first.size() - 1] == '}')) {
144  std::shared_ptr<Anything> value{};
145  value = serdes_registry.deserialize(it.first, it.second);
146  if (value) {
147  TREE_MAP_SET(annotations, value->get_type_index(), value);
148  }
149  }
150  }
151 }
152 
153 } // namespace annotatable
154 TREE_NAMESPACE_END
STL namespace.