| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2011 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 #ifndef CHROME_BROWSER_CHROMEOS_CROS_ENUM_MAPPER_H_ | |
| 6 #define CHROME_BROWSER_CHROMEOS_CROS_ENUM_MAPPER_H_ | |
| 7 | |
| 8 #include <map> | |
| 9 #include <string> | |
| 10 | |
| 11 #include "base/basictypes.h" | |
| 12 | |
| 13 namespace chromeos { | |
| 14 | |
| 15 // This turns an array of string-to-enum-value mappings into a class | |
| 16 // that can cache the mapping and do quick lookups using an actual map | |
| 17 // class. Usage is something like: | |
| 18 // | |
| 19 // const char kKey1[] = "key1"; | |
| 20 // const char kKey2[] = "key2"; | |
| 21 // | |
| 22 // enum EnumFoo { | |
| 23 // UNKNOWN = 0, | |
| 24 // FOO = 1, | |
| 25 // BAR = 2, | |
| 26 // }; | |
| 27 // | |
| 28 // const EnumMapper<EnumFoo>::Pair index_table[] = { | |
| 29 // { kKey1, FOO }, | |
| 30 // { kKey2, BAR }, | |
| 31 // }; | |
| 32 // | |
| 33 // EnumMapper<EnumFoo> mapper(index_table, arraysize(index_table), UNKNOWN); | |
| 34 // EnumFoo value = mapper.Get(kKey1); // Returns FOO. | |
| 35 // EnumFoo value = mapper.Get('boo'); // Returns UNKNOWN. | |
| 36 template <typename EnumType> | |
| 37 class EnumMapper { | |
| 38 public: | |
| 39 struct Pair { | |
| 40 const char* key; | |
| 41 const EnumType value; | |
| 42 }; | |
| 43 | |
| 44 EnumMapper(const Pair* list, size_t num_entries, EnumType unknown) | |
| 45 : unknown_value_(unknown) { | |
| 46 for (size_t i = 0; i < num_entries; ++i, ++list) { | |
| 47 enum_map_[list->key] = list->value; | |
| 48 inverse_enum_map_[list->value] = list->key; | |
| 49 } | |
| 50 } | |
| 51 | |
| 52 EnumType Get(const std::string& type) const { | |
| 53 EnumMapConstIter iter = enum_map_.find(type); | |
| 54 if (iter != enum_map_.end()) | |
| 55 return iter->second; | |
| 56 return unknown_value_; | |
| 57 } | |
| 58 | |
| 59 std::string GetKey(EnumType type) const { | |
| 60 InverseEnumMapConstIter iter = inverse_enum_map_.find(type); | |
| 61 if (iter != inverse_enum_map_.end()) | |
| 62 return iter->second; | |
| 63 return std::string(); | |
| 64 } | |
| 65 | |
| 66 private: | |
| 67 typedef typename std::map<std::string, EnumType> EnumMap; | |
| 68 typedef typename std::map<EnumType, std::string> InverseEnumMap; | |
| 69 typedef typename EnumMap::const_iterator EnumMapConstIter; | |
| 70 typedef typename InverseEnumMap::const_iterator InverseEnumMapConstIter; | |
| 71 EnumMap enum_map_; | |
| 72 InverseEnumMap inverse_enum_map_; | |
| 73 EnumType unknown_value_; | |
| 74 DISALLOW_COPY_AND_ASSIGN(EnumMapper); | |
| 75 }; | |
| 76 | |
| 77 } // namespace chromeos | |
| 78 | |
| 79 #endif // CHROME_BROWSER_CHROMEOS_CROS_ENUM_MAPPER_H_ | |
| OLD | NEW |