Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 23550ef3 authored by Lloyd Pique's avatar Lloyd Pique
Browse files

ftl: contains

ftl::contains(container, value) returns true if the container contains
the value. It's implemented in terms of std::find(), so has the same
runtime complexity.

It is otherwise a simplified version of the C++23 std::ranges::contains,
which has some additional options, and can be deprecated once C++23 is
the minimal supported version.

Test: atest ftl_test
Bug: 185536303
Change-Id: I98aefe7cf6645ac3a20fddfe0657fa6822d669de
parent d50d517f
Loading
Loading
Loading
Loading
+12 −0
Original line number Diff line number Diff line
@@ -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};
+11 −0
Original line number Diff line number Diff line
@@ -23,6 +23,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;