blob: f7716ff68a4479656a861e71e4f3cf4e9723e19f [file] [log] [blame]
Jordan Baylesb5ac6d32020-11-19 15:23:59 -08001// 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
18namespace openscreen {
19
20constexpr 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).
24template <typename Enum, size_t Size>
25using EnumNameTable = std::array<std::pair<const char*, Enum>, Size>;
26
27// Get the name of an enum from the enum value.
28template <typename Enum, size_t Size>
29ErrorOr<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.
40template <typename Enum, size_t Size>
41ErrorOr<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_