diff --git a/src/util/optional_utils.h b/src/util/optional_utils.h new file mode 100644 index 00000000000..59e17ffcad9 --- /dev/null +++ b/src/util/optional_utils.h @@ -0,0 +1,28 @@ +/*******************************************************************\ + + Module: functions that are useful with optionalt + + Author: Diffblue Ltd. + +\*******************************************************************/ + +#ifndef CPROVER_UTIL_OPTIONAL_UTILS_H +#define CPROVER_UTIL_OPTIONAL_UTILS_H + +#include "optional.h" + +/// Lookup a key in a map, if found return the associated value, +/// nullopt otherwise +template +auto optional_lookup(const map_like_collectiont &map, const keyt &key) + -> optionaltsecond)> +{ + auto const it = map.find(key); + if(it != map.end()) + { + return it->second; + } + return nullopt; +} + +#endif // CPROVER_UTIL_OPTIONAL_UTILS_H diff --git a/unit/Makefile b/unit/Makefile index 60d4f36ac0e..8ec9f5a9706 100644 --- a/unit/Makefile +++ b/unit/Makefile @@ -41,6 +41,7 @@ SRC += analyses/ai/ai.cpp \ util/irep_sharing.cpp \ util/message.cpp \ util/optional.cpp \ + util/optional_utils.cpp \ util/pointer_offset_size.cpp \ util/range.cpp \ util/replace_symbol.cpp \ diff --git a/unit/util/optional_utils.cpp b/unit/util/optional_utils.cpp new file mode 100644 index 00000000000..578342b682e --- /dev/null +++ b/unit/util/optional_utils.cpp @@ -0,0 +1,44 @@ +/*******************************************************************\ + + Module: optional_utils unit tests + + Author: Diffblue Ltd. + +\*******************************************************************/ + +#include + +#include + +#include +#include +#include + +namespace +{ +template +void do_optional_lookup_test(map_like_collectiont &map) +{ + map.insert({"hello", "world"}); + map.insert({"pwd", "/home"}); + auto const hello_result = optional_lookup(map, "hello"); + REQUIRE(hello_result.has_value()); + REQUIRE(hello_result.value() == "world"); + auto const pwd_result = optional_lookup(map, "pwd"); + REQUIRE(pwd_result.has_value()); + REQUIRE(pwd_result.value() == "/home"); + REQUIRE_FALSE(optional_lookup(map, "does not exit").has_value()); +} +} // namespace + +TEST_CASE("Using optional_lookup with std::map") +{ + auto map = std::map{}; + do_optional_lookup_test(map); +} + +TEST_CASE("Using optional_lookup with std::unordered_map") +{ + auto map = std::unordered_map{}; + do_optional_lookup_test(map); +}