-
Notifications
You must be signed in to change notification settings - Fork 0
/
factory.hpp
143 lines (113 loc) · 2.28 KB
/
factory.hpp
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/**
* @file
*
* @brief Headerfile of Struct checker
*
* @copyright BSD License (see doc/LICENSE.md or http://www.libelektra.org)
*
*/
#ifndef FACTORY_HPP
#define FACTORY_HPP
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
// TODO: to add a new struct checker, 1.) include your header here
#include "checker.hpp"
namespace elektra
{
class Instancer
{
public:
virtual Checker * get () = 0;
virtual ~Instancer ()
{
}
};
template <class T>
class Cnstancer : public Instancer
{
virtual T * get () override
{
return new T ();
}
};
class StructInstancer : public Instancer
{
kdb::KeySet config;
public:
StructInstancer (kdb::KeySet config_) : config (config_)
{
}
virtual StructChecker * get () override
{
return new StructChecker (config);
}
};
class Factory
{
std::map<std::string, Instancer *> m_factory;
public:
Factory (kdb::KeySet config) : m_factory ()
{
config.rewind ();
kdb::Key root = config.next ();
m_factory.insert (std::make_pair ("list", new Cnstancer<ListChecker> ()));
kdb::Key k;
while ((k = config.next ()))
{
if (!k.isDirectBelow (root)) throw "Factory: key for configuration is not direct below";
kdb::KeySet cks (config.cut (k));
m_factory.insert (std::make_pair (k.getBaseName (), new StructInstancer (cks)));
}
}
~Factory ()
{
for (auto & elem : m_factory)
{
delete elem.second;
}
}
CheckerPtr get (std::string const & which)
{
Instancer * instancer = m_factory[which];
if (instancer)
{
CheckerPtr ret (instancer->get ());
return ret;
}
else
throw "Could not get instance";
}
};
static inline void doCheck (Checker * c, kdb::KeySet ks)
{
try
{
c->check (ks);
}
catch (const char *)
{
/* Make sure that it will be released */
ks.release ();
throw;
}
ks.release ();
}
static inline Checker * buildChecker (kdb::KeySet config)
{
kdb::Key k = config.lookup ("/struct");
if (!k) throw "No Key describing the struct found";
Factory f (config.cut (k));
std::stringstream ss (k.getString ());
std::string whichChecker;
ss >> whichChecker;
CheckerPtr c = f.get (whichChecker);
if (!c.get ()) throw "Could not create list";
std::string whichParameter;
ss >> whichParameter;
c->buildup (f, whichParameter);
return c.release ();
}
} // end namespace elektra
#endif