1 |
root |
1.2 |
#ifndef SHSTR_H__ |
2 |
|
|
#define SHSTR_H__ |
3 |
|
|
|
4 |
root |
1.5 |
extern int buf_overflow(const char *buf1, const char *buf2, int bufsize); |
5 |
|
|
|
6 |
|
|
struct shstr |
7 |
|
|
{ |
8 |
|
|
const char *s; |
9 |
root |
1.4 |
|
10 |
root |
1.7 |
static int &refcnt (const char *s) |
11 |
root |
1.5 |
{ |
12 |
|
|
return *((int *)s - 1); |
13 |
|
|
} |
14 |
|
|
|
15 |
root |
1.7 |
static int &length (const char *s) |
16 |
|
|
{ |
17 |
|
|
return *((int *)s - 2); |
18 |
|
|
} |
19 |
|
|
|
20 |
|
|
int &refcnt () const |
21 |
|
|
{ |
22 |
|
|
return refcnt (s); |
23 |
|
|
} |
24 |
|
|
|
25 |
|
|
int length () const |
26 |
|
|
{ |
27 |
|
|
return s ? length (s) : 0; |
28 |
|
|
} |
29 |
|
|
|
30 |
root |
1.5 |
static const char *find (const char *s); |
31 |
|
|
static const char *intern (const char *s); |
32 |
|
|
|
33 |
|
|
static void gc (); // garbage collect a few strings |
34 |
|
|
|
35 |
root |
1.6 |
// this is used for informational messages and the like |
36 |
root |
1.5 |
const char *operator &() const { return s ? s : "<nil>"; } |
37 |
|
|
|
38 |
root |
1.6 |
const char &operator [](int i) const { return s[i]; } |
39 |
root |
1.5 |
operator const char *() const { return s; } |
40 |
|
|
|
41 |
|
|
shstr () |
42 |
|
|
: s (0) |
43 |
|
|
{ |
44 |
|
|
} |
45 |
|
|
|
46 |
root |
1.6 |
shstr (const shstr &sh) |
47 |
root |
1.5 |
: s (sh.s) |
48 |
|
|
{ |
49 |
|
|
if (s) ++refcnt (); |
50 |
|
|
} |
51 |
|
|
|
52 |
|
|
explicit shstr (const char *s) |
53 |
|
|
: s (intern (s)) |
54 |
|
|
{ |
55 |
|
|
} |
56 |
|
|
|
57 |
|
|
~shstr () |
58 |
|
|
{ |
59 |
|
|
if (s) --refcnt (); |
60 |
|
|
} |
61 |
|
|
|
62 |
|
|
const shstr &operator =(const shstr &sh) |
63 |
|
|
{ |
64 |
|
|
if (s) --refcnt (); |
65 |
|
|
s = sh.s; |
66 |
|
|
if (s) ++refcnt (); |
67 |
|
|
|
68 |
|
|
return *this; |
69 |
|
|
} |
70 |
|
|
|
71 |
|
|
const shstr &operator =(const char *str) |
72 |
|
|
{ |
73 |
|
|
if (s) --refcnt (); |
74 |
|
|
s = intern (str); |
75 |
root |
1.1 |
|
76 |
root |
1.5 |
return *this; |
77 |
|
|
} |
78 |
|
|
}; |
79 |
root |
1.1 |
|
80 |
root |
1.5 |
inline int strlen (const shstr &sh) |
81 |
|
|
{ |
82 |
|
|
return sh.length (); |
83 |
|
|
} |
84 |
root |
1.2 |
|
85 |
root |
1.5 |
inline bool operator ==(const shstr &a, const shstr &b) |
86 |
|
|
{ |
87 |
|
|
return a.s == b.s; |
88 |
|
|
} |
89 |
root |
1.4 |
|
90 |
root |
1.5 |
inline bool operator !=(const shstr &a, const shstr &b) |
91 |
root |
1.4 |
{ |
92 |
root |
1.5 |
return !(a == b); |
93 |
|
|
} |
94 |
root |
1.4 |
|
95 |
root |
1.2 |
#endif |
96 |
|
|
|