Skip to content

Commit 82efc96

Browse files
committed
[ADT] Add set_intersects to check if there is any intersection
Add a facility to check if there is any intersection between 2 sets. This will be used in some follow on changes to MemProf.
1 parent 8337d01 commit 82efc96

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

llvm/include/llvm/ADT/SetOperations.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,23 @@ bool set_is_subset(const S1Ty &S1, const S2Ty &S2) {
157157
return true;
158158
}
159159

160+
template <class S1Ty, class S2Ty>
161+
bool set_intersects_impl(const S1Ty &S1, const S2Ty &S2) {
162+
for (const auto &E : S1)
163+
if (S2.count(E))
164+
return true;
165+
return false;
166+
}
167+
168+
/// set_intersects(A, B) - Return true iff A ^ B is non empty
169+
template <class S1Ty, class S2Ty>
170+
bool set_intersects(const S1Ty &S1, const S2Ty &S2) {
171+
if (S1.size() < S2.size())
172+
return set_intersects_impl(S1, S2);
173+
else
174+
return set_intersects_impl(S2, S1);
175+
}
176+
160177
} // namespace llvm
161178

162179
#endif

llvm/unittests/ADT/SetOperationsTest.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,4 +273,15 @@ TEST(SetOperationsTest, SetIsSubset) {
273273
EXPECT_FALSE(set_is_subset(Set1, Set2));
274274
}
275275

276+
TEST(SetOperationsTest, SetIntersects) {
277+
std::set<int> Set1 = {1, 2, 3, 4};
278+
std::set<int> Set2 = {3, 4, 5};
279+
EXPECT_TRUE(set_intersects(Set1, Set2));
280+
EXPECT_TRUE(set_intersects(Set2, Set1));
281+
282+
Set2 = {5, 6, 7};
283+
EXPECT_FALSE(set_intersects(Set1, Set2));
284+
EXPECT_FALSE(set_intersects(Set2, Set1));
285+
}
286+
276287
} // namespace

0 commit comments

Comments
 (0)