From a1623638274d8bb47668a17c1c0d0a7c57452eee Mon Sep 17 00:00:00 2001 From: Yevgeny Rouban Date: Wed, 6 Nov 2019 11:17:51 +0700 Subject: [PATCH] [ADT] Add equality operator for SmallPtrSet Reviewed By: tellenbach Differential Revision: https://reviews.llvm.org/D69429 --- include/llvm/ADT/SmallPtrSet.h | 26 +++++++++++++++++++++ unittests/ADT/SmallPtrSetTest.cpp | 38 +++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/include/llvm/ADT/SmallPtrSet.h b/include/llvm/ADT/SmallPtrSet.h index 913518230d2..1d8280063c8 100644 --- a/include/llvm/ADT/SmallPtrSet.h +++ b/include/llvm/ADT/SmallPtrSet.h @@ -409,6 +409,32 @@ private: } }; +/// Equality comparison for SmallPtrSet. +/// +/// Iterates over elements of LHS confirming that each value from LHS is also in +/// RHS, and that no additional values are in RHS. +template +bool operator==(const SmallPtrSetImpl &LHS, + const SmallPtrSetImpl &RHS) { + if (LHS.size() != RHS.size()) + return false; + + for (const auto *KV : LHS) + if (!RHS.count(KV)) + return false; + + return true; +} + +/// Inequality comparison for SmallPtrSet. +/// +/// Equivalent to !(LHS == RHS). +template +bool operator!=(const SmallPtrSetImpl &LHS, + const SmallPtrSetImpl &RHS) { + return !(LHS == RHS); +} + /// SmallPtrSet - This class implements a set which is optimized for holding /// SmallSize or less elements. This internally rounds up SmallSize to the next /// power of two if it is not already a power of two. See the comments above diff --git a/unittests/ADT/SmallPtrSetTest.cpp b/unittests/ADT/SmallPtrSetTest.cpp index cff1632586b..3226fe61550 100644 --- a/unittests/ADT/SmallPtrSetTest.cpp +++ b/unittests/ADT/SmallPtrSetTest.cpp @@ -329,3 +329,41 @@ TEST(SmallPtrSetTest, ConstNonPtrTest) { EXPECT_EQ(IntSet.count(Pair), 1u); EXPECT_NE(IntSet.find(Pair), IntSet.end()); } + +// Test equality comparison. +TEST(SmallPtrSetTest, EqualityComparison) { + int buf[3]; + for (int i = 0; i < 3; ++i) + buf[i] = 0; + + SmallPtrSet a; + a.insert(&buf[0]); + a.insert(&buf[1]); + + SmallPtrSet b; + b.insert(&buf[1]); + b.insert(&buf[0]); + + SmallPtrSet c; + c.insert(&buf[1]); + c.insert(&buf[2]); + + SmallPtrSet d; + d.insert(&buf[0]); + + SmallPtrSet e; + e.insert(&buf[0]); + e.insert(&buf[1]); + e.insert(&buf[2]); + + EXPECT_EQ(a, b); + EXPECT_EQ(b, a); + EXPECT_NE(b, c); + EXPECT_NE(c, a); + EXPECT_NE(d, a); + EXPECT_NE(a, d); + EXPECT_NE(a, e); + EXPECT_NE(e, a); + EXPECT_NE(c, e); + EXPECT_NE(e, d); +}