constant_mapping.h
Go to the documentation of this file.
1 
11 #pragma once
12 
13 #include <vector>
14 #include <functional>
15 #include "interop/util/map.h"
16 #include "interop/util/length_of.h"
17 
18 namespace illumina { namespace interop { namespace util
19 {
20 
21  namespace detail
22  {
25  struct enum_hash
26  {
32  template<typename T>
33  std::size_t operator()(const T val)const
34  {
35  return static_cast<std::size_t>(val);
36  }
37 #ifdef INTEROP_HAS_UNORDERED_MAP
38 
43  std::size_t operator()(const std::string& val)const
44  {
45  return std::hash<std::string>{}(val);
46  }
47 #endif
48  };
49  }
50 
53  template<class Key, class Value>
55  {
56  typedef INTEROP_UNORDERED_HASHMAP(Key, Value, detail::enum_hash) constant_map_t;
57  private:
58  constant_mapping(const std::pair<Key, Value>* pairs, size_t n)
59  {
60  for (size_t i = 0; i < n; ++i)
61  {
62  m_mapping.insert(std::make_pair(pairs[i].first, pairs[i].second));
63  }
64  }
65  constant_mapping(const std::pair<Value, Key>* pairs, size_t n)
66  {
67  for (size_t i = 0; i < n; ++i)
68  {
69  m_mapping.insert(std::make_pair(pairs[i].second, pairs[i].first));
70  }
71  }
72 
73  public:
80  static const constant_mapping<Key, Value> &fmapping(const std::pair<Key, Value>* pairs, size_t pair_count)
81  {
82  static constant_mapping<Key, Value> singleton(pairs, pair_count); // Only called once
83  return singleton;
84  }
92  static const constant_mapping<Key, Value> &rmapping(const std::pair<Value, Key>* pairs, size_t pair_count)
93  {
94  static constant_mapping<Key, Value> singleton(pairs, pair_count); // Only called once
95  return singleton;
96  }
103  const Value &get(const Key &key, const Value &default_value) const
104  {
105  typename constant_map_t::const_iterator it = m_mapping.find(key);
106  if (it == m_mapping.end()) return default_value;
107  return it->second;
108  }
109 
110  private:
111  constant_map_t m_mapping;
112  };
113 
121  template<class Key, class Value, size_t N>
122  const Value &constant_mapping_get(const std::pair<Key, Value> (&pairs)[N], const Key &key,
123  const Value &default_value)
124  {
125  return constant_mapping<Key, Value>::fmapping(pairs, N).get(key, default_value);
126  }
127 
128 }}}
129 
static const constant_mapping< Key, Value > & rmapping(const std::pair< Value, Key > *pairs, size_t pair_count)
Definition: constant_mapping.h:92
Definition: enum_description.h:15
const Value & constant_mapping_get(const std::pair< Key, Value >(&pairs)[N], const Key &key, const Value &default_value)
Definition: constant_mapping.h:122
Definition: constant_mapping.h:54
Definition: constant_mapping.h:25
Definition: enums.h:301
std::size_t operator()(const T val) const
Definition: constant_mapping.h:33
static const constant_mapping< Key, Value > & fmapping(const std::pair< Key, Value > *pairs, size_t pair_count)
Definition: constant_mapping.h:80