• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 //
5 // This file contains helpers for working with enums that require
6 // both enum->string and string->enum conversions.
7 
8 #ifndef UTIL_ENUM_NAME_TABLE_H_
9 #define UTIL_ENUM_NAME_TABLE_H_
10 
11 #include <array>
12 #include <utility>
13 
14 #include "absl/strings/string_view.h"
15 #include "platform/base/error.h"
16 #include "util/osp_logging.h"
17 
18 namespace openscreen {
19 
20 constexpr char kUnknownEnumError[] = "Enum value not in array";
21 
22 // TODO(jophba): move to a proper class once we can inherit from array
23 // properly (in C++17).
24 template <typename Enum, size_t Size>
25 using EnumNameTable = std::array<std::pair<const char*, Enum>, Size>;
26 
27 // Get the name of an enum from the enum value.
28 template <typename Enum, size_t Size>
GetEnumName(const EnumNameTable<Enum,Size> & map,Enum enum_)29 ErrorOr<const char*> GetEnumName(const EnumNameTable<Enum, Size>& map,
30                                  Enum enum_) {
31   for (auto pair : map) {
32     if (pair.second == enum_) {
33       return pair.first;
34     }
35   }
36   return Error(Error::Code::kParameterInvalid, kUnknownEnumError);
37 }
38 
39 // Get the value of an enum from the enum name.
40 template <typename Enum, size_t Size>
GetEnum(const EnumNameTable<Enum,Size> & map,absl::string_view name)41 ErrorOr<Enum> GetEnum(const EnumNameTable<Enum, Size>& map,
42                       absl::string_view name) {
43   for (auto pair : map) {
44     if (pair.first == name) {
45       return pair.second;
46     }
47   }
48   return Error(Error::Code::kParameterInvalid, kUnknownEnumError);
49 }
50 
51 }  // namespace openscreen
52 #endif  // UTIL_ENUM_NAME_TABLE_H_
53