diff options
author | 2022-11-15 11:34:33 -0500 | |
---|---|---|
committer | 2023-04-18 19:28:35 -0400 | |
commit | 80872bddcc529d750c12349675504ea00271712a (patch) | |
tree | 3e151d2772fe229b1bc94d11d718294e1af2427c /include/ftl | |
parent | ccda33e2eb762b0f9ffff3de982011b6fc7f84ec (diff) |
SF: Clean up ftl::SmallMap lookup fallbacks
Avoid std::cref to a local variable, which is not intuitive and incurs
construction in the non-fallback case.
Bug: 185536303
Test: ftl_test
Change-Id: I1c5a94bdab105a04f8230fe762bdc433eea5c97a
Diffstat (limited to 'include/ftl')
-rw-r--r-- | include/ftl/algorithm.h | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/include/ftl/algorithm.h b/include/ftl/algorithm.h index c5ff03b80d..c0f67683ab 100644 --- a/include/ftl/algorithm.h +++ b/include/ftl/algorithm.h @@ -68,4 +68,29 @@ constexpr auto to_mapped_ref(const Pair& pair) -> std::reference_wrapper<const M return std::cref(pair.second); } +// Combinator for ftl::Optional<T>::or_else when T is std::reference_wrapper<const V>. Given a +// lambda argument that returns a `constexpr` value, ftl::static_ref<T> binds a reference to a +// static T initialized to that constant. +// +// const ftl::SmallMap map = ftl::init::map(13, "tiramisu"sv)(14, "upside-down cake"sv); +// assert("???"sv == +// map.get(20).or_else(ftl::static_ref<std::string_view>([] { return "???"sv; }))->get()); +// +// using Map = decltype(map); +// +// assert("snow cone"sv == +// ftl::find_if(map, [](const auto& pair) { return pair.second.front() == 's'; }) +// .transform(ftl::to_mapped_ref<Map>) +// .or_else(ftl::static_ref<std::string_view>([] { return "snow cone"sv; })) +// ->get()); +// +template <typename T, typename F> +constexpr auto static_ref(F&& f) { + return [f = std::forward<F>(f)] { + constexpr auto kInitializer = f(); + static const T kValue = kInitializer; + return Optional(std::cref(kValue)); + }; +} + } // namespace android::ftl |