Skip to content

Commit 60c6202

Browse files
[ADT] Add set_intersects to check if there is any intersection (#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.
1 parent 404af37 commit 60c6202

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

llvm/include/llvm/ADT/SetOperations.h

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

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

162182
#endif

llvm/unittests/ADT/SetOperationsTest.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,4 +273,21 @@ 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+
// Check that intersecting with a null set returns false.
287+
Set1.clear();
288+
EXPECT_FALSE(set_intersects(Set1, Set2));
289+
EXPECT_FALSE(set_intersects(Set2, Set1));
290+
EXPECT_FALSE(set_intersects(Set1, Set1));
291+
}
292+
276293
} // namespace

0 commit comments

Comments
 (0)