-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_pool.hh
77 lines (68 loc) · 1.6 KB
/
string_pool.hh
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
#ifndef STRING_POOL_HH
#define STRING_POOL_HH
#include <cstdlib>
#ifdef __GNUC__
#if __GNUC__ > 2
using namespace std;
#endif
#endif
/******************************************************************************/
/* Class that allocates a const char* if not yet present in string pool */
/******************************************************************************/
// table of all locks a thread is holding
#ifdef HASH_TABLE
#include <hash_set>
#else
#include <set>
#endif
#ifdef HASH_TABLE
struct eqstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) == 0;
}
};
typedef hash_set<const char*, hash<const char*>, eqstr> string_table;
#else
struct ltstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) < 0;
}
};
typedef set<const char*, ltstr> string_table;
#endif
class string_pool {
public:
string_table pool;
const char* add(const char* el) {
char* entry;
string_table::iterator it;
if ((it = pool.find(el)) == pool.end()) {
// allocate element!
entry = strdup(el);
pool.insert(entry);
return const_cast<const char*>(entry);
} else {
return *it;
}
}
void remove(const char* el) {
string_table::iterator entry;
if ((entry = pool.find(el)) != pool.end()) {
// free space for element
free(const_cast<char*>(*entry));
pool.erase(entry);
}
}
void clear() {
// TODO: protect iter pointer
for (string_table::iterator it = pool.begin(); it != pool.end(); ++it) {
free(const_cast<char*>(*it));
pool.erase(it);
}
}
};
#endif