3 #include "../../src/hashtable.h"
4 #include "gtest/gtest.h"
6 typedef uint64_t Value
;
8 class HashTableTest
: public testing::Test
11 static const int HT_SIZE
= 1024;
14 HashTableTest() : ht(HT_SIZE
) {}
16 Hash
hash_from_index(int i
) const {
17 return static_cast<Hash
>(i
& (ht
.size() - 1));
21 TEST_F(HashTableTest
, Size
)
23 HashTable
<Value
> ht2(HT_SIZE
);
24 EXPECT_EQ(sizeof(ht2
), sizeof(ht
));
26 int entry_size
= sizeof(Hash
) + sizeof(Value
);
27 EXPECT_EQ(16, entry_size
);
29 int size
= HT_SIZE
/ entry_size
;
31 // 'size' must be a power of two for HashTable<T>::lookup()
32 EXPECT_EQ(0, size
& (size
- 1));
34 EXPECT_EQ(size
, ht
.size());
37 TEST_F(HashTableTest
, Constructor
)
40 const int n
= ht
.size();
41 for (int i
= 0; i
< n
; ++i
) {
42 EXPECT_EQ(0, ht
.hash_at(i
));
43 EXPECT_EQ(0, ht
.value_at(i
));
47 TEST_F(HashTableTest
, ConstructorWithoutClear
)
49 const int n
= ht
.size();
50 for (int i
= 0; i
< n
; ++i
) {
51 EXPECT_EQ(0, ht
.hash_at(i
));
52 EXPECT_EQ(0, ht
.value_at(i
));
56 TEST_F(HashTableTest
, Clear
)
58 const int n
= ht
.size();
59 for (int i
= 0; i
< n
; ++i
) {
60 Hash h
= hash_from_index(i
);
63 EXPECT_EQ(h
, ht
.hash_at(i
));
64 EXPECT_EQ(i
, ht
.value_at(i
));
67 for (int i
= 0; i
< n
; ++i
) {
68 EXPECT_EQ(0, ht
.hash_at(i
));
69 EXPECT_EQ(0, ht
.value_at(i
));
73 TEST_F(HashTableTest
, Lookup
)
75 const int n
= ht
.size();
76 for (int i
= 0; i
< n
; ++i
) {
77 Hash h
= hash_from_index(i
);
79 Value v
= ht
.lookup(h
, &is_empty
);
83 EXPECT_FALSE(is_empty
);
85 EXPECT_TRUE(is_empty
);
88 for (int i
= -1; i
< n
; ++i
) {
89 for (int s
= SHRT_MIN
; s
<= SHRT_MAX
; s
+= 1000) {
92 Value v
= static_cast<Value
>(s
+ i
);
93 Hash h
= hash_from_index(i
);
97 EXPECT_EQ(h
, ht
.hash_at(i
));
98 EXPECT_EQ(v
, ht
.value_at(i
));
99 EXPECT_NE(0, ht
.value_at(i
));
102 for (int i
= -1; i
< n
; ++i
) {
103 for (int s
= SHRT_MIN
; s
<= SHRT_MAX
; s
+= 1000) {
106 Value v
= static_cast<Value
>(s
+ i
);
107 Hash h
= hash_from_index(i
);
112 Value v2
= ht
.lookup(h
, &is_empty
);
113 EXPECT_FALSE(is_empty
);
119 TEST(MaterialTableTest
, Size
)
121 HashTable
<Material
> ht(MT_SIZE
);
123 int entry_size
= sizeof(Hash
) + sizeof(Material
);
124 EXPECT_EQ(16, entry_size
);
126 int size
= MT_SIZE
/ entry_size
;
128 // 'size' must be a power of two for HashTable<Material>::lookup()
129 EXPECT_EQ(0, size
& (size
- 1));
131 EXPECT_EQ(size
, ht
.size());