1/* 2 * Copyright 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#ifndef A_LOOKUP_H_ 18 19#define A_LOOKUP_H_ 20 21#include <utility> 22#include <vector> 23 24namespace android { 25 26template<typename T, typename U> 27struct ALookup { 28 ALookup(std::initializer_list<std::pair<T, U>> list); 29 30 bool lookup(const T& from, U *to) const; 31 bool rlookup(const U& from, T *to) const; 32 33 template<typename V, typename = typename std::enable_if<!std::is_same<T, V>::value>::type> 34 inline bool map(const T& from, V *to) const { return lookup(from, to); } 35 36 template<typename V, typename = typename std::enable_if<!std::is_same<T, V>::value>::type> 37 inline bool map(const V& from, T *to) const { return rlookup(from, to); } 38 39private: 40 std::vector<std::pair<T, U>> mTable; 41}; 42 43template<typename T, typename U> 44ALookup<T, U>::ALookup(std::initializer_list<std::pair<T, U>> list) 45 : mTable(list) { 46} 47 48template<typename T, typename U> 49bool ALookup<T, U>::lookup(const T& from, U *to) const { 50 for (auto elem : mTable) { 51 if (elem.first == from) { 52 *to = elem.second; 53 return true; 54 } 55 } 56 return false; 57} 58 59template<typename T, typename U> 60bool ALookup<T, U>::rlookup(const U& from, T *to) const { 61 for (auto elem : mTable) { 62 if (elem.second == from) { 63 *to = elem.first; 64 return true; 65 } 66 } 67 return false; 68} 69 70} // namespace android 71 72#endif // A_UTILS_H_ 73