… | |
… | |
6 | #include <cstdlib> |
6 | #include <cstdlib> |
7 | |
7 | |
8 | #include <tr1/unordered_set> |
8 | #include <tr1/unordered_set> |
9 | |
9 | |
10 | #include "shstr.h" |
10 | #include "shstr.h" |
11 | |
|
|
12 | // NOTE: even with lots of stuff loaded, we do not usually have >>20000 strings. |
|
|
13 | // maybe refcounting is just overhead? |
|
|
14 | |
11 | |
15 | struct hash |
12 | struct hash |
16 | { |
13 | { |
17 | std::size_t operator ()(const char *s) const |
14 | std::size_t operator ()(const char *s) const |
18 | { |
15 | { |
… | |
… | |
49 | |
46 | |
50 | typedef std::tr1::unordered_set<const char *, hash, equal> HT; |
47 | typedef std::tr1::unordered_set<const char *, hash, equal> HT; |
51 | |
48 | |
52 | static HT ht; |
49 | static HT ht; |
53 | |
50 | |
|
|
51 | static const char *makevec (const char *s) |
|
|
52 | { |
|
|
53 | int len = strlen (s); |
|
|
54 | |
|
|
55 | const char *v = (const char *)(2 + (int *)malloc (sizeof (int) * 2 + len + 1)); |
|
|
56 | |
|
|
57 | shstr::length (v) = len; |
|
|
58 | shstr::refcnt (v) = 1; |
|
|
59 | |
|
|
60 | memcpy ((char *)v, s, len + 1); |
|
|
61 | |
|
|
62 | return v; |
|
|
63 | } |
|
|
64 | |
|
|
65 | const char *shstr::null = makevec ("<nil>"); |
|
|
66 | |
|
|
67 | // what weird misoptimisation is this again? |
|
|
68 | const shstr undead_name ("undead"); |
|
|
69 | |
54 | const char * |
70 | const char * |
55 | shstr::find (const char *s) |
71 | shstr::find (const char *s) |
56 | { |
72 | { |
57 | if (!s) |
73 | if (!s) |
58 | return s; |
74 | return s; |
… | |
… | |
66 | |
82 | |
67 | const char * |
83 | const char * |
68 | shstr::intern (const char *s) |
84 | shstr::intern (const char *s) |
69 | { |
85 | { |
70 | if (!s) |
86 | if (!s) |
71 | return s; |
87 | return null; |
72 | |
88 | |
73 | if (const char *found = find (s)) |
89 | if (const char *found = find (s)) |
74 | { |
90 | { |
75 | ++refcnt (found); |
91 | ++refcnt (found); |
76 | return found; |
92 | return found; |
77 | } |
93 | } |
78 | |
94 | |
79 | int len = strlen (s); |
95 | s = makevec (s); |
80 | |
|
|
81 | const char *v = (const char *)(2 + (int *)malloc (sizeof (int) * 2 + len + 1)); |
|
|
82 | |
|
|
83 | length (v) = len; |
|
|
84 | refcnt (v) = 1; |
|
|
85 | |
|
|
86 | memcpy ((char *)v, s, len + 1); |
|
|
87 | |
|
|
88 | ht.insert (v); |
96 | ht.insert (s); |
89 | |
|
|
90 | return v; |
97 | return s; |
91 | } |
98 | } |
92 | |
99 | |
93 | // periodically test refcounts == 0 for a few strings |
100 | // periodically test refcounts == 0 for a few strings |
94 | // this is the ONLY thing that erases stuff from ht. keep it that way. |
101 | // this is the ONLY thing that erases stuff from ht. keep it that way. |
95 | void |
102 | void |