From 7ea70322e1e44f3e7163ac2764136e9eb283c312 Mon Sep 17 00:00:00 2001 From: Chris Hawley Date: Sun, 1 Dec 2024 09:04:39 -0800 Subject: [PATCH] Normalize folly::get_optional for nested map case 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(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 --- folly/container/MapUtil.h | 16 ++++++++++++---- folly/container/test/MapUtilTest.cpp | 5 +++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/folly/container/MapUtil.h b/folly/container/MapUtil.h index b134595db49..7935f6cd4e0 100644 --- a/folly/container/MapUtil.h +++ b/folly/container/MapUtil.h @@ -272,14 +272,22 @@ auto extract_default(const KeysDefault&... keysDefault) -> * Given a map of maps and a path of keys, return a Optional if the nested * key exists and None if the nested keys does not exist in the map. */ -template +template < + template 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::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(pos->second, key2, keys...); + } else { + return {}; + } } /** diff --git a/folly/container/test/MapUtilTest.cpp b/folly/container/test/MapUtilTest.cpp index 42b16d34d80..fe0fd8bb1a1 100644 --- a/folly/container/test/MapUtilTest.cpp +++ b/folly/container/test/MapUtilTest.cpp @@ -106,6 +106,11 @@ TEST(MapUtil, getOptionalStd) { EXPECT_TRUE(get_optional(m, 1).has_value()); EXPECT_EQ(2, get_optional(m, 1).value()); EXPECT_FALSE(get_optional(m, 2).has_value()); + + std::map> m2{{1, {{2, 3}}}}; + EXPECT_TRUE(get_optional(m2, 1, 2).has_value()); + EXPECT_EQ(3, get_optional(m2, 1, 2).value()); + EXPECT_FALSE(get_optional(m2, 1, 3).has_value()); } TEST(MapUtil, getRefDefault) {