Skip to content

[ADT] Add set_intersects to check if there is any intersection #127907

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider putting this in a detail namespace

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

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));
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you also add a testcase with empty sets (the usual source of edge cases)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


} // namespace