OdbDesign
OdbDesign ODB++ Parser - C++ library, gRPC/REST server, CLI, tests
 
Loading...
Searching...
No Matches
EnumMap.h
Go to the documentation of this file.
1#pragma once
2
3#include <vector>
4#include <string>
5#include <exception>
6#include "str_utils.h"
7#include <algorithm>
8#include <iterator>
9
10namespace Utils
11{
12 template<typename E>
13 class EnumMap
14 {
15 public:
16 EnumMap(const std::vector<std::string>& names, bool caseInsensitive = false);
17
18 const std::string& getValue(const E e) const;
19 E getValue(const std::string& name) const;
20
21 bool contains(const std::string& name) const;
22 bool contains(const E e) const;
23
24 //typedef std::exception Exception;
25
26 private:
27 const std::vector<std::string> m_names;
28 const bool m_bCaseInsensitive;
29
30 };
31
32 template<typename E>
33 inline EnumMap<E>::EnumMap(const std::vector<std::string>& names, bool caseInsensitive)
34 : m_names(names)
35 , m_bCaseInsensitive(caseInsensitive)
36 {}
37
38 template<typename E>
39 inline const std::string& EnumMap<E>::getValue(const E e) const
40 {
41 auto index = static_cast<size_t>(e);
42 if (index < 0 || index >= m_names.size())
43 {
44 std::string msg = "no name found for value: " + std::to_string(index);
45 throw std::invalid_argument(msg.c_str());
46 }
47 return m_names[index];
48 }
49
50 template<typename E>
51 inline E EnumMap<E>::getValue(const std::string& name) const
52 {
53 std::vector<std::string>::const_iterator findIt;
54 if (m_bCaseInsensitive)
55 {
56 findIt = Utils::find_str_icmp(m_names.begin(), m_names.end(), name);
57 }
58 else
59 {
60 findIt = std::find(m_names.begin(), m_names.end(), name);
61 }
62
63 if (findIt == m_names.end())
64 {
65 std::string msg = "no value found for name: (" + name + ")";
66 throw std::invalid_argument(msg.c_str());
67 }
68 return static_cast<E>(std::distance(m_names.begin(), findIt));
69 }
70
71 template<typename E>
72 inline bool EnumMap<E>::contains(const std::string& name) const
73 {
74 return std::find(m_names.begin(), m_names.end(), name) != m_names.end();
75 }
76
77 template<typename E>
78 inline bool EnumMap<E>::contains(const E e) const
79 {
80 auto index = static_cast<size_t>(e);
81 return index >= 0 && index < m_names.size();
82 }
83}
const std::string & getValue(const E e) const
Definition EnumMap.h:39
bool contains(const E e) const
Definition EnumMap.h:78
E getValue(const std::string &name) const
Definition EnumMap.h:51
bool contains(const std::string &name) const
Definition EnumMap.h:72
EnumMap(const std::vector< std::string > &names, bool caseInsensitive=false)
Definition EnumMap.h:33
std::vector< std::string >::iterator find_str_icmp(std::vector< std::string >::iterator first, std::vector< std::string >::iterator last, const std::string &val)