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