15 #include "../core/math_func.hpp"
17 template <
class Titem_>
20 typedef typename Titem_::Key Key;
27 inline void Clear() {m_pFirst = NULL;}
30 inline const Titem_ *
Find(
const Key& key)
const
32 for (
const Titem_ *pItem = m_pFirst; pItem != NULL; pItem = pItem->GetHashNext()) {
33 if (pItem->GetKey() == key) {
42 inline Titem_ *
Find(
const Key& key)
44 for (Titem_ *pItem = m_pFirst; pItem != NULL; pItem = pItem->GetHashNext()) {
45 if (pItem->GetKey() == key) {
56 assert(new_item.GetHashNext() == NULL);
57 new_item.SetHashNext(m_pFirst);
62 inline bool Detach(Titem_& item_to_remove)
64 if (m_pFirst == &item_to_remove) {
65 m_pFirst = item_to_remove.GetHashNext();
66 item_to_remove.SetHashNext(NULL);
69 Titem_ *pItem = m_pFirst;
74 Titem_ *pNextItem = pItem->GetHashNext();
75 if (pNextItem == &item_to_remove)
break;
78 pItem->SetHashNext(item_to_remove.GetHashNext());
79 item_to_remove.SetHashNext(NULL);
84 inline Titem_ *
Detach(
const Key& key)
87 if (m_pFirst == NULL) {
91 if (m_pFirst->GetKey() == key) {
92 Titem_& ret_item = *m_pFirst;
93 m_pFirst = m_pFirst->GetHashNext();
94 ret_item.SetHashNext(NULL);
98 Titem_ *pPrev = m_pFirst;
99 for (Titem_ *pItem = m_pFirst->GetHashNext(); pItem != NULL; pPrev = pItem, pItem = pItem->GetHashNext()) {
100 if (pItem->GetKey() == key) {
102 pPrev->SetHashNext(pItem->GetHashNext());
103 pItem->SetHashNext(NULL);
133 template <
class Titem_,
int Thash_bits_>
136 typedef Titem_ Titem;
137 typedef typename Titem_::Key Tkey;
138 static const int Thash_bits = Thash_bits_;
139 static const int Tcapacity = 1 << Thash_bits;
148 Slot m_slots[Tcapacity];
161 int32 hash = key.CalcHash();
162 if ((8 * Thash_bits) < 32) hash ^= hash >> (
min(8 * Thash_bits, 31));
163 if ((4 * Thash_bits) < 32) hash ^= hash >> (
min(4 * Thash_bits, 31));
164 if ((2 * Thash_bits) < 32) hash ^= hash >> (
min(2 * Thash_bits, 31));
165 if ((1 * Thash_bits) < 32) hash ^= hash >> (
min(1 * Thash_bits, 31));
166 hash &= (1 << Thash_bits) - 1;
175 inline int Count()
const {
return m_num_items;}
178 inline void Clear() {
for (
int i = 0; i < Tcapacity; i++) m_slots[i].
Clear();}
181 const Titem_ *
Find(
const Tkey& key)
const
184 const Slot& slot = m_slots[hash];
185 const Titem_ *item = slot.
Find(key);
193 Slot& slot = m_slots[hash];
194 Titem_ *item = slot.
Find(key);
202 Slot& slot = m_slots[hash];
203 Titem_ *item = slot.
Detach(key);
211 Titem_&
Pop(
const Tkey& key)
213 Titem_ *item =
TryPop(key);
214 assert(item != NULL);
221 const Tkey& key = item.GetKey();
223 Slot& slot = m_slots[hash];
224 bool ret = slot.
Detach(item);
242 Slot& slot = m_slots[hash];
243 assert(slot.
Find(new_item.GetKey()) == NULL);