Skip to content

Instantly share code, notes, and snippets.

@ckerr
Created June 15, 2023 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ckerr/abb24130ff8ffdcb3bc686b80c027633 to your computer and use it in GitHub Desktop.
Save ckerr/abb24130ff8ffdcb3bc686b80c027633 to your computer and use it in GitHub Desktop.
namespace gin {
namespace detail {
// Get a key from `key_val` and check `lookup` for a matching entry.
// Return true iff a match is found, and set `*out` to the entry's value.
template <typename KeyType, typename Out, typename Map>
bool FromV8WithLookup(
v8::Isolate* isolate,
v8::Local<v8::Value> key_val,
const Map& table,
Out* out,
std::function<void(KeyType&)> transform = [](KeyType&) {}) {
static_assert(std::is_same_v<typename Map::mapped_type, Out>);
auto key = KeyType{};
if (!ConvertFromV8(isolate, key_val, &key))
return false;
transform(key);
if (const auto* iter = table.find(key); iter != table.end()) {
*out = iter->second;
return true;
}
return false;
}
} // namespace detail
// Convert `key_val to a string key and check `lookup` for a matching entry.
// Return true iff a match is found, and set `*out` to the entry's value.
template <typename Out, typename Map>
bool FromV8WithLookup(v8::Isolate* isolate,
v8::Local<v8::Value> key_val,
const Map& table,
Out* out) {
return detail::FromV8WithLookup<std::string>(isolate, key_val, table, out);
}
// Convert `key_val to a lowercase string key and check `lookup` for a matching
// entry. Return true iff a match is found, and set `*out` to the entry's value.
template <typename Out, typename Map>
bool FromV8WithLowerLookup(v8::Isolate* isolate,
v8::Local<v8::Value> key_val,
const Map& table,
Out* out) {
static constexpr auto to_lower_ascii_inplace = [](std::string& str) {
for (auto& ch : str)
ch = base::ToLowerASCII(ch);
};
return detail::FromV8WithLookup<std::string>(isolate, key_val, table, out,
to_lower_ascii_inplace);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment