From e4213f5767620382378232419a6e49ec35fef1ad Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Thu, 14 Mar 2024 12:48:09 -0400 Subject: [PATCH] AK: Generalize Span::contains_slow to use the Traits infrastructure This allows, for example, checking if a Span contains a value without having to allocate a String. --- AK/Span.h | 5 +++-- Tests/AK/TestSpan.cpp | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/AK/Span.h b/AK/Span.h index b61bf079de..de72faf0c9 100644 --- a/AK/Span.h +++ b/AK/Span.h @@ -210,10 +210,11 @@ public: return size(); } - [[nodiscard]] constexpr bool contains_slow(T const& value) const + template + [[nodiscard]] constexpr bool contains_slow(V const& value) const { for (size_t i = 0; i < size(); ++i) { - if (at(i) == value) + if (Traits>::equals(at(i), value)) return true; } return false; diff --git a/Tests/AK/TestSpan.cpp b/Tests/AK/TestSpan.cpp index 098b34bd47..cfb14fb86a 100644 --- a/Tests/AK/TestSpan.cpp +++ b/Tests/AK/TestSpan.cpp @@ -138,3 +138,24 @@ TEST_CASE(starts_with) ReadonlyBytes hey_bytes_u8 { hey_array, 3 }; EXPECT(bytes.starts_with(hey_bytes_u8)); } + +TEST_CASE(contains_slow) +{ + Vector list { "abc"_string, "def"_string, "ghi"_string }; + auto span = list.span(); + + EXPECT(span.contains_slow("abc"_string)); + EXPECT(span.contains_slow("abc"sv)); + + EXPECT(span.contains_slow("def"_string)); + EXPECT(span.contains_slow("def"sv)); + + EXPECT(span.contains_slow("ghi"_string)); + EXPECT(span.contains_slow("ghi"sv)); + + EXPECT(!span.contains_slow("whf"_string)); + EXPECT(!span.contains_slow("whf"sv)); + + EXPECT(!span.contains_slow(String {})); + EXPECT(!span.contains_slow(StringView {})); +}