enum_names.hpp
1 // Copyright (C) 2018-2021 Intel Corporation
2 // SPDX-License-Identifier: Apache-2.0
3 //
4 
5 #pragma once
6 
7 #include <algorithm>
8 #include <string>
9 #include <utility>
10 
11 #include "ngraph/check.hpp"
12 
13 namespace ngraph
14 {
15  /// Uses a pairings defined by EnumTypes::get() to convert between strings
16  /// and enum values.
17  template <typename EnumType>
18  class EnumNames
19  {
20  public:
21  /// Converts strings to enum values
22  static EnumType as_enum(const std::string& name)
23  {
24  auto to_lower = [](const std::string& s) {
25  std::string rc = s;
26  std::transform(rc.begin(), rc.end(), rc.begin(), [](char c) {
27  return static_cast<char>(::tolower(static_cast<int>(c)));
28  });
29  return rc;
30  };
31  for (auto p : get().m_string_enums)
32  {
33  if (to_lower(p.first) == to_lower(name))
34  {
35  return p.second;
36  }
37  }
38  NGRAPH_CHECK(false, "\"", name, "\"", " is not a member of enum ", get().m_enum_name);
39  }
40 
41  /// Converts enum values to strings
42  static const std::string& as_string(EnumType e)
43  {
44  for (auto& p : get().m_string_enums)
45  {
46  if (p.second == e)
47  {
48  return p.first;
49  }
50  }
51  NGRAPH_CHECK(false, " invalid member of enum ", get().m_enum_name);
52  }
53 
54  private:
55  /// Creates the mapping.
56  EnumNames(const std::string& enum_name,
57  const std::vector<std::pair<std::string, EnumType>> string_enums)
58  : m_enum_name(enum_name)
59  , m_string_enums(string_enums)
60  {
61  }
62 
63  /// Must be defined to returns a singleton for each supported enum class
64  static EnumNames<EnumType>& get();
65 
66  const std::string m_enum_name;
67  std::vector<std::pair<std::string, EnumType>> m_string_enums;
68  };
69 
70  /// Returns the enum value matching the string
71  template <typename Type, typename Value>
72  typename std::enable_if<std::is_convertible<Value, std::string>::value, Type>::type
73  as_enum(const Value& value)
74  {
75  return EnumNames<Type>::as_enum(value);
76  }
77 
78  /// Returns the string matching the enum value
79  template <typename Value>
80  const std::string& as_string(Value value)
81  {
82  return EnumNames<Value>::as_string(value);
83  }
84 } // namespace ngraph
Definition: enum_names.hpp:19
static const std::string & as_string(EnumType e)
Converts enum values to strings.
Definition: enum_names.hpp:42
static EnumType as_enum(const std::string &name)
Converts strings to enum values.
Definition: enum_names.hpp:22
The Intel nGraph C++ API.
Definition: attribute_adapter.hpp:16
std::enable_if< std::is_convertible< Value, std::string >::value, Type >::type as_enum(const Value &value)
Returns the enum value matching the string.
Definition: enum_names.hpp:73
const std::string & as_string(Value value)
Returns the string matching the enum value.
Definition: enum_names.hpp:80