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