Skip to content

Commit

Permalink
Alternative approach with unordered_map
Browse files Browse the repository at this point in the history
  • Loading branch information
fjahr committed Feb 21, 2024
1 parent 3918736 commit cbda2cf
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 6 deletions.
10 changes: 4 additions & 6 deletions src/rpc/util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,7 @@ RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RP
// there can be pairs of POSITIONAL and NAMED parameters with the same name.
enum ParamType { POSITIONAL = 1, NAMED = 2, NAMED_ONLY = 4 };
std::map<std::string, int> param_names;
size_t arg_index{0};

for (const auto& arg : m_args) {
std::vector<std::string> names = SplitString(arg.m_names, '|');
Expand All @@ -529,6 +530,7 @@ RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RP
CHECK_NONFATAL(!(param_type & POSITIONAL));
CHECK_NONFATAL(!(param_type & NAMED_ONLY));
param_type |= POSITIONAL;
m_arg_names.emplace(name, arg_index);
}
if (arg.m_type == RPCArg::Type::OBJ_NAMED_PARAMS) {
for (const auto& inner : arg.m_inner) {
Expand Down Expand Up @@ -569,6 +571,7 @@ RPCHelpMan::RPCHelpMan(std::string name, std::string description, std::vector<RP
break;
}
}
++arg_index;
}
}

Expand Down Expand Up @@ -719,12 +722,7 @@ std::vector<std::pair<std::string, bool>> RPCHelpMan::GetArgNames() const

size_t RPCHelpMan::GetParamIndex(std::string_view key) const
{
auto it{std::find_if(
m_args.begin(), m_args.end(), [&key](const auto& arg) { return arg.GetName() == key;}
)};

CHECK_NONFATAL(it != m_args.end()); // TODO: ideally this is checked at compile time
return std::distance(m_args.begin(), it);
return m_arg_names.at(static_cast<std::string>(key));
}

std::string RPCHelpMan::ToString() const
Expand Down
1 change: 1 addition & 0 deletions src/rpc/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,7 @@ class RPCHelpMan
const std::vector<RPCArg> m_args;
const RPCResults m_results;
const RPCExamples m_examples;
std::unordered_map<std::string, size_t> m_arg_names; // Map argument names to their index in m_args
mutable const JSONRPCRequest* m_req{nullptr}; // A pointer to the request for the duration of m_fun()
template <typename R>
R ArgValue(size_t i) const;
Expand Down

0 comments on commit cbda2cf

Please sign in to comment.