mirror of
https://github.com/ethereum/solidity
synced 2023-10-03 13:03:40 +00:00
Merge pull request #10739 from ethereum/mapFetchValue
Add fetchValue utility for maps.
This commit is contained in:
commit
e9dcd4f813
@ -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>{});
|
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.
|
// String conversion functions, mainly to/from hex/nibble/byte representations.
|
||||||
|
|
||||||
enum class WhenError
|
enum class WhenError
|
||||||
|
Loading…
Reference in New Issue
Block a user