Skip to content

Commit

Permalink
Normalize folly::get_optional for nested map case
Browse files Browse the repository at this point in the history
Summary:
`folly::get_optional` allows the user to specify the optional type, e.g.
```
// default case - return folly::Optional
get_optional(m, 1);

// return std::optional
get_optional<std::optional>(m, 1);
```

`folly::get_optional` also supports nested maps, however it hardcodes the return type to always be `folly::Optional`. This diff relaxes the constraints and allows the user to specify optional type, defaulting to `folly::Optional`

Reviewed By: Gownta

Differential Revision: D66497266

fbshipit-source-id: bef87007956c7df8c7c07a0e70716b18e770e90d
  • Loading branch information
cjhawley authored and facebook-github-bot committed Dec 1, 2024
1 parent b59298f commit 7ea7032
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
16 changes: 12 additions & 4 deletions folly/container/MapUtil.h
Original file line number Diff line number Diff line change
Expand Up @@ -272,14 +272,22 @@ auto extract_default(const KeysDefault&... keysDefault) ->
* Given a map of maps and a path of keys, return a Optional<V> if the nested
* key exists and None if the nested keys does not exist in the map.
*/
template <class Map, class Key1, class Key2, class... Keys>
template <
template <typename> class Optional = folly::Optional,
class Map,
class Key1,
class Key2,
class... Keys>
auto get_optional(
const Map& map, const Key1& key1, const Key2& key2, const Keys&... keys)
-> folly::Optional<
-> Optional<
typename detail::NestedMapType<Map, 2 + sizeof...(Keys)>::type> {
auto pos = map.find(key1);
return pos != map.end() ? get_optional(pos->second, key2, keys...)
: folly::none;
if (pos != map.end()) {
return get_optional<Optional>(pos->second, key2, keys...);
} else {
return {};
}
}

/**
Expand Down
5 changes: 5 additions & 0 deletions folly/container/test/MapUtilTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ TEST(MapUtil, getOptionalStd) {
EXPECT_TRUE(get_optional<std::optional>(m, 1).has_value());
EXPECT_EQ(2, get_optional<std::optional>(m, 1).value());
EXPECT_FALSE(get_optional<std::optional>(m, 2).has_value());

std::map<int, std::map<int, int>> m2{{1, {{2, 3}}}};
EXPECT_TRUE(get_optional<std::optional>(m2, 1, 2).has_value());
EXPECT_EQ(3, get_optional<std::optional>(m2, 1, 2).value());
EXPECT_FALSE(get_optional<std::optional>(m2, 1, 3).has_value());
}

TEST(MapUtil, getRefDefault) {
Expand Down

0 comments on commit 7ea7032

Please sign in to comment.