Skip to content

Commit

Permalink
Automerge: [ADT] Add set_intersects to check if there is any intersec…
Browse files Browse the repository at this point in the history
…tion (#127907)

Add a facility to check if there is any intersection between 2 sets.
This will be used in some follow on changes to MemProf.
  • Loading branch information
teresajohnson authored and github-actions[bot] committed Feb 20, 2025
2 parents 709c3e8 + 60c6202 commit 2803c09
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
20 changes: 20 additions & 0 deletions llvm/include/llvm/ADT/SetOperations.h
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,26 @@ bool set_is_subset(const S1Ty &S1, const S2Ty &S2) {
return true;
}

namespace detail {

template <class S1Ty, class S2Ty>
bool set_intersects_impl(const S1Ty &S1, const S2Ty &S2) {
for (const auto &E : S1)
if (S2.count(E))
return true;
return false;
}

} // namespace detail

/// set_intersects(A, B) - Return true iff A ^ B is non empty
template <class S1Ty, class S2Ty>
bool set_intersects(const S1Ty &S1, const S2Ty &S2) {
if (S1.size() < S2.size())
return detail::set_intersects_impl(S1, S2);
return detail::set_intersects_impl(S2, S1);
}

} // namespace llvm

#endif
17 changes: 17 additions & 0 deletions llvm/unittests/ADT/SetOperationsTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -273,4 +273,21 @@ TEST(SetOperationsTest, SetIsSubset) {
EXPECT_FALSE(set_is_subset(Set1, Set2));
}

TEST(SetOperationsTest, SetIntersects) {
std::set<int> Set1 = {1, 2, 3, 4};
std::set<int> Set2 = {3, 4, 5};
EXPECT_TRUE(set_intersects(Set1, Set2));
EXPECT_TRUE(set_intersects(Set2, Set1));

Set2 = {5, 6, 7};
EXPECT_FALSE(set_intersects(Set1, Set2));
EXPECT_FALSE(set_intersects(Set2, Set1));

// Check that intersecting with a null set returns false.
Set1.clear();
EXPECT_FALSE(set_intersects(Set1, Set2));
EXPECT_FALSE(set_intersects(Set2, Set1));
EXPECT_FALSE(set_intersects(Set1, Set1));
}

} // namespace

0 comments on commit 2803c09

Please sign in to comment.