- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
template <typename Key, typename Value, size_t TblPower = 2>
struct HashMap {
struct Node
{
Key k;
Value v;
Node *n;
Node(const Key &key, const Value &value) :
k(key), v(value), n(NULL) {}
Node(const Key &key) :
k(key), v(), n(NULL) {}
};
constexpr static size_t TblSize = 1U << TblPower;
Node *table[TblSize] = {nullptr};
HashMap() {
}
~HashMap() {
for(size_t i = 0; i < TblSize; i++)
{
Node *entry = table[i];
while(entry)
{
Node *prev = entry;
entry = entry->n;
delete prev;
}
table[i] = NULL;
}
}
size_t HashFunc(const Key &key) const
{
/// TODO: string hash?
// handle hash: handle pointers usually aligned
return (((size_t) key) >> 8) & (TblSize - 1);
}
// just in case: check existance or constant access
forceinline Value *GetPtr(const Key &key) const
{
size_t hashValue = HashFunc(key);
Node *entry = table[hashValue];
while(likely(entry))
{
if(entry->k == key)
return &entry->v;
entry = entry->n;
}
return nullptr;
}
Value &operator [] (const Key &key)
{
return GetOrAllocate(key);
}
#define HASHFIND(key) \
size_t hashValue = HashFunc(key); \
Node *prev = NULL; \
Node *entry = table[hashValue]; \
\
while(entry && entry->k != key) \
{ \
prev = entry; \
entry = entry->n; \
}
Node * noinline _Allocate(Key key, size_t hashValue, Node *prev, Node *entry)
{
entry = new Node(key);
if(unlikely(!entry))
{
static Node error(key);
return &error;
}
if(prev == NULL)
table[hashValue] = entry;
else
prev->n = entry;
return entry;
}
Value& GetOrAllocate(const Key &key)
{
HASHFIND(key);
if(unlikely(!entry))
entry = _Allocate(key,hashValue, prev, entry);
return entry->v;
}
// тут был ещё один метод, но в говнокод не влез
}
Комментарии (0) RSS
Добавить комментарий