Skip to content

Commit 873a8ae

Browse files
committed
Make IntSet hashable.
So it can be used with flat_hash_set/map.
1 parent 88eaad4 commit 873a8ae

File tree

3 files changed

+35
-4
lines changed

3 files changed

+35
-4
lines changed

common/BUILD

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,5 +113,6 @@ cc_test(
113113
":mocks",
114114
"@googletest//:gtest_main",
115115
"@abseil-cpp//absl/container:btree",
116+
"@abseil-cpp//absl/hash:hash_test",
116117
],
117118
)

common/int_set.h

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,10 +140,14 @@ class IntSet {
140140
return a == this->end();
141141
}
142142

143-
// TODO(garretrieger): add union, intersection etc.
143+
template <typename H>
144+
friend H AbslHashValue(H h, const IntSet& set) {
145+
// Utilize the existing harfbuzz hashing function.
146+
unsigned harfbuzz_hash = hb_set_hash(set.set_.get());
147+
return H::combine(std::move(h), harfbuzz_hash);
148+
}
144149

145-
// TODO(garretrieger): add absl hashing support so we can use these in
146-
// hash_sets/maps
150+
// TODO(garretrieger): add union, intersection etc.
147151

148152
iterator begin() { return iterator(set_.get()); }
149153

common/int_set_test.cc

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
#include "common/hb_set_unique_ptr.h"
44
#include "gtest/gtest.h"
5+
#include "absl/hash/hash_testing.h"
56

67
namespace common {
78

@@ -200,6 +201,31 @@ TEST_F(IntSetTest, UseInBtreeSet) {
200201
ASSERT_EQ(*it, empty);
201202
}
202203

203-
// TODO(garretrieger): test use in hash and btree, sets and maps.
204+
TEST_F(IntSetTest, UseInHashSet) {
205+
absl::flat_hash_set<IntSet> sets{{7, 8, 11}, {7, 8}, {7, 8, 12}, {}};
206+
207+
IntSet empty{};
208+
IntSet a{7, 8};
209+
IntSet b{7, 8, 11};
210+
IntSet c{7, 8, 12};
211+
IntSet d{8, 11};
212+
213+
ASSERT_TRUE(sets.contains(empty));
214+
ASSERT_TRUE(sets.contains(a));
215+
ASSERT_TRUE(sets.contains(b));
216+
ASSERT_TRUE(sets.contains(c));
217+
ASSERT_FALSE(sets.contains(d));
218+
}
219+
220+
TEST_F(IntSetTest, SupportsAbslHash) {
221+
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({
222+
IntSet {},
223+
IntSet {7, 8},
224+
IntSet {7, 8, 11},
225+
IntSet {7, 8, 12},
226+
IntSet {8, 11},
227+
IntSet {7, 8, 12},
228+
}));
229+
}
204230

205231
} // namespace common

0 commit comments

Comments
 (0)