blob: ecd6fdc121996dd06b2853e768d89ad2095e9fb4 (
plain)
1
2
3
4
5
6
7
8
9
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
|
#ifndef __JE_COMMON_SREINGMAP_H__
#define __JE_COMMON_SREINGMAP_H__
#include "object.h"
namespace JinEngine
{
template<typename T, unsigned SIZE>
class StringMap : public Object
{
private:
struct Record
{
const char * key;
T value;
bool set;
Record() : set(false) {}
};
const static unsigned MAX = SIZE * 2;
Record records[MAX];
const char * reverse[SIZE];
public:
struct Entry
{
const char * key;
T value;
};
StringMap(Entry * entries, unsigned num)
{
for (unsigned i = 0; i < SIZE; ++i)
reverse[i] = 0;
unsigned n = num / sizeof(Entry);
for (unsigned i = 0; i < n; ++i)
{
add(entries[i].key, entries[i].value);
}
}
bool streq(const char * a, const char * b)
{
while (*a != 0 && *b != 0)
{
if (*a != *b)
return false;
++a;
++b;
}
return (*a == 0 && *b == 0);
}
bool find(const char * key, T & t)
{
//unsigned str_hash = djb2(key);
for (unsigned i = 0; i < MAX; ++i)
{
//unsigned str_i = (str_hash + i) % MAX; //this isn't used, is this intentional?
if (records[i].set && streq(records[i].key, key))
{
t = records[i].value;
return true;
}
}
return false;
}
bool find(T key, const char *& str)
{
unsigned index = (unsigned)key;
if (index >= SIZE)
return false;
if (reverse[index] != 0)
{
str = reverse[index];
return true;
}
else
{
return false;
}
}
bool add(const char * key, T value)
{
unsigned str_hash = djb2(key);
bool inserted = false;
for (unsigned i = 0; i < MAX; ++i)
{
unsigned str_i = (str_hash + i) % MAX;
if (!records[str_i].set)
{
inserted = true;
records[str_i].set = true;
records[str_i].key = key;
records[str_i].value = value;
break;
}
}
unsigned index = (unsigned)value;
if (index >= SIZE)
{
printf("\nConstant %s out of bounds with %i!\n", key, index);
return false;
}
reverse[index] = key;
return inserted;
}
unsigned djb2(const char * key)
{
unsigned hash = 5381;
int c;
while ((c = *key++))
hash = ((hash << 5) + hash) + c;
return hash;
}
}; // StringMap
} // namespace JinEngine
#endif
|