Skip to content

Commit

Permalink
Merge pull request ethereum#10739 from ethereum/mapFetchValue
Browse files Browse the repository at this point in the history
Add fetchValue utility for maps.
  • Loading branch information
chriseth authored Jan 12, 2021
2 parents 162b150 + f5adaa8 commit e9dcd4f
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions libsolutil/CommonData.h
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,39 @@ std::set<K> keys(std::map<K, V> const& _map)
return applyMap(_map, [](auto const& _elem) { return _elem.first; }, std::set<K>{});
}

/// @returns a pointer to the entry of @a _map at @a _key, if there is one, and nullptr otherwise.
template<typename MapType, typename KeyType>
decltype(auto) valueOrNullptr(MapType&& _map, KeyType const& _key)
{
auto it = _map.find(_key);
return (it == _map.end()) ? nullptr : &it->second;
}

namespace detail
{
struct allow_copy {};
}
static constexpr auto allow_copy = detail::allow_copy{};

/// @returns a reference to the entry of @a _map at @a _key, if there is one, and @a _defaultValue otherwise.
/// Makes sure no copy is involved, unless allow_copy is passed as fourth argument.
template<
typename MapType,
typename KeyType,
typename ValueType = std::decay_t<decltype(std::declval<MapType>().find(std::declval<KeyType>())->second)> const&,
typename AllowCopyType = void*
>
decltype(auto) valueOrDefault(MapType&& _map, KeyType const& _key, ValueType&& _defaultValue = {}, AllowCopyType = nullptr)
{
auto it = _map.find(_key);
static_assert(
std::is_same_v<AllowCopyType, detail::allow_copy> ||
std::is_reference_v<decltype((it == _map.end()) ? _defaultValue : it->second)>,
"valueOrDefault does not allow copies by default. Pass allow_copy as additional argument, if you want to allow copies."
);
return (it == _map.end()) ? _defaultValue : it->second;
}

// String conversion functions, mainly to/from hex/nibble/byte representations.

enum class WhenError
Expand Down

0 comments on commit e9dcd4f

Please sign in to comment.