1 /* 2 * Copyright (C) 2015 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 _INIT_KEYWORD_MAP_H_ 18 #define _INIT_KEYWORD_MAP_H_ 19 20 #include <map> 21 #include <string> 22 23 #include <android-base/stringprintf.h> 24 25 namespace android { 26 namespace init { 27 28 template <typename Function> 29 class KeywordMap { 30 public: 31 using FunctionInfo = std::tuple<std::size_t, std::size_t, Function>; 32 using Map = std::map<std::string, FunctionInfo>; 33 34 virtual ~KeywordMap() { 35 } 36 37 const Function FindFunction(const std::vector<std::string>& args, std::string* err) const { 38 using android::base::StringPrintf; 39 40 if (args.empty()) { 41 *err = "keyword needed, but not provided"; 42 return nullptr; 43 } 44 auto& keyword = args[0]; 45 auto num_args = args.size() - 1; 46 47 auto function_info_it = map().find(keyword); 48 if (function_info_it == map().end()) { 49 *err = StringPrintf("invalid keyword '%s'", keyword.c_str()); 50 return nullptr; 51 } 52 53 auto function_info = function_info_it->second; 54 55 auto min_args = std::get<0>(function_info); 56 auto max_args = std::get<1>(function_info); 57 if (min_args == max_args && num_args != min_args) { 58 *err = StringPrintf("%s requires %zu argument%s", 59 keyword.c_str(), min_args, 60 (min_args > 1 || min_args == 0) ? "s" : ""); 61 return nullptr; 62 } 63 64 if (num_args < min_args || num_args > max_args) { 65 if (max_args == std::numeric_limits<decltype(max_args)>::max()) { 66 *err = StringPrintf("%s requires at least %zu argument%s", 67 keyword.c_str(), min_args, 68 min_args > 1 ? "s" : ""); 69 } else { 70 *err = StringPrintf("%s requires between %zu and %zu arguments", 71 keyword.c_str(), min_args, max_args); 72 } 73 return nullptr; 74 } 75 76 return std::get<Function>(function_info); 77 } 78 79 private: 80 // Map of keyword -> 81 // (minimum number of arguments, maximum number of arguments, function pointer) 82 virtual const Map& map() const = 0; 83 }; 84 85 } // namespace init 86 } // namespace android 87 88 #endif 89