1 |
/* |
2 |
* shstr.C |
3 |
*/ |
4 |
|
5 |
#include <cstring> |
6 |
#include <cstdlib> |
7 |
|
8 |
#include <tr1/unordered_set> |
9 |
|
10 |
#include "shstr.h" |
11 |
|
12 |
struct hash |
13 |
{ |
14 |
std::size_t operator ()(const char *s) const |
15 |
{ |
16 |
unsigned long hash = 0; |
17 |
unsigned int i = 0; |
18 |
|
19 |
/* use the one-at-a-time hash function, which supposedly is |
20 |
* better than the djb2-like one used by perl5.005, but |
21 |
* certainly is better then the bug used here before. |
22 |
* see http://burtleburtle.net/bob/hash/doobs.html |
23 |
*/ |
24 |
while (*s) |
25 |
{ |
26 |
hash += *s++; |
27 |
hash += hash << 10; |
28 |
hash ^= hash >> 6; |
29 |
} |
30 |
|
31 |
hash += hash << 3; |
32 |
hash ^= hash >> 11; |
33 |
hash += hash << 15; |
34 |
|
35 |
return hash; |
36 |
} |
37 |
}; |
38 |
|
39 |
struct equal |
40 |
{ |
41 |
bool operator ()(const char *a, const char *b) const |
42 |
{ |
43 |
return !strcmp (a, b); |
44 |
} |
45 |
}; |
46 |
|
47 |
typedef std::tr1::unordered_set<const char *, hash, equal> HT; |
48 |
|
49 |
static HT ht; |
50 |
|
51 |
const char * |
52 |
shstr::find (const char *s) |
53 |
{ |
54 |
if (!s) |
55 |
return s; |
56 |
|
57 |
HT::iterator i = ht.find (s); |
58 |
|
59 |
return i != ht.end () |
60 |
? (char *)*i |
61 |
: 0; |
62 |
} |
63 |
|
64 |
const char * |
65 |
shstr::intern (const char *s) |
66 |
{ |
67 |
if (!s) |
68 |
return s; |
69 |
|
70 |
if (const char *found = find (s)) |
71 |
return found; |
72 |
|
73 |
int len = strlen (s); |
74 |
|
75 |
int *v = (int *)malloc (sizeof (int) * 2 + len + 1); |
76 |
|
77 |
v [0] = len; |
78 |
v [1] = 0; |
79 |
|
80 |
v += 2; |
81 |
|
82 |
memcpy (v, s, len + 1); |
83 |
|
84 |
ht.insert ((char *)v); |
85 |
|
86 |
return (char *)v; |
87 |
} |
88 |
|
89 |
// TODO: periodically test refcounts == 0 for a few strings (e.g. one hash bucket, |
90 |
// exploiting the fatc that iterators stay valid for unordered_set). |
91 |
void |
92 |
shstr::gc () |
93 |
{ |
94 |
} |
95 |
|
96 |
/* buf_overflow() - we don't want to exceed the buffer size of |
97 |
* buf1 by adding on buf2! Returns true if overflow will occur. |
98 |
*/ |
99 |
|
100 |
int |
101 |
buf_overflow (const char *buf1, const char *buf2, int bufsize) |
102 |
{ |
103 |
int len1 = 0, len2 = 0; |
104 |
|
105 |
if (buf1) |
106 |
len1 = strlen (buf1); |
107 |
if (buf2) |
108 |
len2 = strlen (buf2); |
109 |
if ((len1 + len2) >= bufsize) |
110 |
return 1; |
111 |
return 0; |
112 |
} |
113 |
|