diff --git a/folly/MapUtil.h b/folly/MapUtil.h index 2586337..b00bccf 100644 --- a/folly/MapUtil.h +++ b/folly/MapUtil.h @@ -17,6 +17,9 @@ #ifndef FOLLY_MAPUTIL_H_ #define FOLLY_MAPUTIL_H_ +#include +#include + namespace folly { /** @@ -32,6 +35,36 @@ typename Map::mapped_type get_default( return (pos != map.end() ? pos->second : dflt); } +/** + * Given a map and a key, return the value corresponding to the key in the map, + * or throw an exception of the specified type. + */ +template +typename Map::mapped_type get_or_throw( + const Map& map, const typename Map::key_type& key, + const std::string& exceptionStrPrefix = std::string()) { + auto pos = map.find(key); + if (pos != map.end()) { + return pos->second; + } + throw E(folly::to(exceptionStrPrefix, key)); +} + +/** + * Given a map and a key, return a Optional if the key exists and None if the + * key does not exist in the map. + */ +template +folly::Optional get_optional( + const Map& map, const typename Map::key_type& key) { + auto pos = map.find(key); + if (pos != map.end()) { + return folly::Optional(pos->second); + } else { + return folly::none; + } +} + /** * Given a map and a key, return a reference to the value corresponding to the * key in the map, or the given default reference if the key doesn't exist in diff --git a/folly/test/MapUtilTest.cpp b/folly/test/MapUtilTest.cpp index 4bb3974..f6d6902 100644 --- a/folly/test/MapUtilTest.cpp +++ b/folly/test/MapUtilTest.cpp @@ -29,6 +29,28 @@ TEST(MapUtil, get_default) { EXPECT_EQ(0, get_default(m, 3)); } +TEST(MapUtil, get_or_throw) { + std::map m; + m[1] = 2; + EXPECT_EQ(2, get_or_throw(m, 1)); + EXPECT_THROW(get_or_throw(m, 2), std::out_of_range); +} + +TEST(MapUtil, get_or_throw_specified) { + std::map m; + m[1] = 2; + EXPECT_EQ(2, get_or_throw(m, 1)); + EXPECT_THROW(get_or_throw(m, 2), std::runtime_error); +} + +TEST(MapUtil, get_optional) { + std::map m; + m[1] = 2; + EXPECT_TRUE(get_optional(m, 1)); + EXPECT_EQ(2, get_optional(m, 1).value()); + EXPECT_FALSE(get_optional(m, 2)); +} + TEST(MapUtil, get_ref_default) { std::map m; m[1] = 2;