diff options
-rw-r--r-- | include/ftl/algorithm.h | 12 | ||||
-rw-r--r-- | libs/ftl/algorithm_test.cpp | 11 |
2 files changed, 23 insertions, 0 deletions
diff --git a/include/ftl/algorithm.h b/include/ftl/algorithm.h index c0f67683ab..68826bb068 100644 --- a/include/ftl/algorithm.h +++ b/include/ftl/algorithm.h @@ -24,6 +24,18 @@ namespace android::ftl { +// Determines if a container contains a value. This is a simplified version of the C++23 +// std::ranges::contains function. +// +// const ftl::StaticVector vector = {1, 2, 3}; +// assert(ftl::contains(vector, 1)); +// +// TODO: Remove in C++23. +template <typename Container, typename Value> +auto contains(const Container& container, const Value& value) -> bool { + return std::find(container.begin(), container.end(), value) != container.end(); +} + // Adapter for std::find_if that converts the return value from iterator to optional. // // const ftl::StaticVector vector = {"upside"sv, "down"sv, "cake"sv}; diff --git a/libs/ftl/algorithm_test.cpp b/libs/ftl/algorithm_test.cpp index 487b1b8759..11569f22c7 100644 --- a/libs/ftl/algorithm_test.cpp +++ b/libs/ftl/algorithm_test.cpp @@ -24,6 +24,17 @@ namespace android::test { // Keep in sync with example usage in header file. +TEST(Algorithm, Contains) { + const ftl::StaticVector vector = {1, 2, 3}; + EXPECT_TRUE(ftl::contains(vector, 1)); + + EXPECT_FALSE(ftl::contains(vector, 0)); + EXPECT_TRUE(ftl::contains(vector, 2)); + EXPECT_TRUE(ftl::contains(vector, 3)); + EXPECT_FALSE(ftl::contains(vector, 4)); +} + +// Keep in sync with example usage in header file. TEST(Algorithm, FindIf) { using namespace std::string_view_literals; |