From 558fb0a04ae33609a62d4d29de9d89ce0cdd7b13 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Wed, 5 Jan 2022 17:00:17 +0100 Subject: [PATCH] AK: Make Vector::remove_all_matching() return removal success This matches the behavior of other remove_*_matching() functions. --- AK/Vector.h | 5 ++++- Tests/AK/TestVector.cpp | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/AK/Vector.h b/AK/Vector.h index d04b34f83dc..4dcedf933a3 100644 --- a/AK/Vector.h +++ b/AK/Vector.h @@ -405,15 +405,18 @@ public: } template - void remove_all_matching(TUnaryPredicate predicate) + bool remove_all_matching(TUnaryPredicate predicate) { + bool something_was_removed = false; for (size_t i = 0; i < size();) { if (predicate(at(i))) { remove(i); + something_was_removed = true; } else { ++i; } } + return something_was_removed; } ALWAYS_INLINE T take_last() diff --git a/Tests/AK/TestVector.cpp b/Tests/AK/TestVector.cpp index bf3d807431b..2289c246397 100644 --- a/Tests/AK/TestVector.cpp +++ b/Tests/AK/TestVector.cpp @@ -259,6 +259,29 @@ TEST_CASE(vector_remove) EXPECT_EQ(ints[0], 4); } +TEST_CASE(remove_all_matching) +{ + Vector ints; + + ints.append(1); + ints.append(2); + ints.append(3); + ints.append(4); + + EXPECT_EQ(ints.size(), 4u); + + EXPECT_EQ(ints.remove_all_matching([&](int value) { return value > 2; }), true); + EXPECT_EQ(ints.remove_all_matching([&](int) { return false; }), false); + + EXPECT_EQ(ints.size(), 2u); + + EXPECT_EQ(ints.remove_all_matching([&](int) { return true; }), true); + + EXPECT(ints.is_empty()); + + EXPECT_EQ(ints.remove_all_matching([&](int) { return true; }), false); +} + TEST_CASE(nonnullownptrvector) { struct Object {