summaryrefslogtreecommitdiff
path: root/src/include/tome/enum_string_map.hpp
diff options
context:
space:
mode:
authorBardur Arantsson <bardur@scientician.net>2012-06-19 20:03:42 +0200
committerBardur Arantsson <bardur@scientician.net>2013-09-27 14:46:40 +0200
commitb05113a48a2031282b5f4e65b97407a7bc8438c1 (patch)
treeab5042ebb89b8a6b5728b6843c22608c14e21393 /src/include/tome/enum_string_map.hpp
parent1d65909b257cc84282da4a1192072615b716138c (diff)
C++: Move Automatizer to C++
Diffstat (limited to 'src/include/tome/enum_string_map.hpp')
-rw-r--r--src/include/tome/enum_string_map.hpp58
1 files changed, 58 insertions, 0 deletions
diff --git a/src/include/tome/enum_string_map.hpp b/src/include/tome/enum_string_map.hpp
new file mode 100644
index 00000000..80ba7833
--- /dev/null
+++ b/src/include/tome/enum_string_map.hpp
@@ -0,0 +1,58 @@
+#ifndef H_ae6d0de3_c72e_4e67_9da2_975283fbd009
+#define H_ae6d0de3_c72e_4e67_9da2_975283fbd009
+
+#include <boost/bimap.hpp>
+#include <boost/noncopyable.hpp>
+#include <string>
+#include <cassert>
+
+/**
+ * Bidirectional mapping between enumerated values
+ * and strings.
+ */
+template <class E>
+class EnumStringMap : boost::noncopyable {
+
+private:
+ typedef boost::bimap< E, std::string > bimap_type;
+ typedef typename bimap_type::value_type value_type;
+
+ bimap_type bimap;
+
+public:
+ explicit EnumStringMap(std::initializer_list< std::pair<E, const char *> > in) {
+ for (auto es : in)
+ {
+ bimap.insert(value_type(es.first, es.second));
+ }
+ // Sanity check that there were no
+ // duplicate mappings.
+ assert(bimap.size() == in.size());
+ }
+
+ const char *stringify(E e) {
+ auto i = bimap.left.find(e);
+ assert(i != bimap.left.end() && "Missing mapping for enumerated value");
+ return i->second.c_str();
+ }
+
+ E parse(const char *s) {
+ E e;
+ bool result = parse(s, &e);
+ assert(result && "Missing string->enum mapping");
+ return e;
+ }
+
+ bool parse(const char *s, E *e) {
+ auto i = bimap.right.find(s);
+ if (i == bimap.right.end())
+ {
+ return false;
+ }
+
+ *e = i->second;
+ return true;
+ }
+};
+
+#endif