| 1 |
#ifndef SHSTR_H |
| 2 |
#define SHSTR_H |
| 3 |
|
| 4 |
#include <string> |
| 5 |
#include <vector> |
| 6 |
#include <iostream> |
| 7 |
|
| 8 |
#include <glib.h> |
| 9 |
|
| 10 |
#ifdef WANT_STRLEN |
| 11 |
# define WANT_STRLEN 1 |
| 12 |
#else |
| 13 |
# define WANT_STRLEN 0 |
| 14 |
#endif |
| 15 |
|
| 16 |
#if WANT_STRLEN |
| 17 |
# define SHSTRLEN(str) strlen (str) |
| 18 |
#else |
| 19 |
# define SHSTRLEN(str) 0 |
| 20 |
#endif |
| 21 |
|
| 22 |
struct shentry |
| 23 |
{ |
| 24 |
shentry (char const *str, const size_t hash) |
| 25 |
: m_refcnt (0), m_str (str), m_len (SHSTRLEN (str)), m_hash (hash) |
| 26 |
{ |
| 27 |
} |
| 28 |
|
| 29 |
void *operator new (size_t n) |
| 30 |
{ |
| 31 |
return g_slice_alloc (n); |
| 32 |
} |
| 33 |
|
| 34 |
void operator delete (void *ptr, size_t n) |
| 35 |
{ |
| 36 |
g_slice_free1 (n, ptr); |
| 37 |
} |
| 38 |
|
| 39 |
size_t m_refcnt; |
| 40 |
char const * const m_str; |
| 41 |
size_t m_len; |
| 42 |
size_t m_hash; |
| 43 |
}; |
| 44 |
|
| 45 |
class shstr |
| 46 |
{ |
| 47 |
public: |
| 48 |
static char const *insert (char const *str, size_t *size); |
| 49 |
|
| 50 |
static void erase (char const *str); |
| 51 |
|
| 52 |
static size_t refs (char const *str); |
| 53 |
static size_t strcnt (); |
| 54 |
|
| 55 |
static size_t memused (); |
| 56 |
|
| 57 |
protected: |
| 58 |
static size_t m_cnt; |
| 59 |
|
| 60 |
static size_t m_bucketcnt; |
| 61 |
|
| 62 |
typedef std::vector<shentry *> pairs; |
| 63 |
|
| 64 |
static pairs *m_buckets; |
| 65 |
|
| 66 |
static shentry *prepare (char const *str); |
| 67 |
static bool unref (char const *str); |
| 68 |
static const shentry *get (char const *str); |
| 69 |
|
| 70 |
static pairs::iterator find (char const *str, size_t n); |
| 71 |
|
| 72 |
static size_t hash (char const *str); |
| 73 |
|
| 74 |
public: |
| 75 |
void *operator new (size_t n) |
| 76 |
{ |
| 77 |
return g_slice_alloc (n); |
| 78 |
} |
| 79 |
|
| 80 |
void operator delete (void *ptr, size_t n) |
| 81 |
{ |
| 82 |
g_slice_free1 (n, ptr); |
| 83 |
} |
| 84 |
|
| 85 |
typedef size_t size_type; |
| 86 |
|
| 87 |
shstr (char const *str = ""); |
| 88 |
shstr (const shstr &rhs); |
| 89 |
~shstr (); |
| 90 |
|
| 91 |
char const *c_str () const; |
| 92 |
size_type length () const; |
| 93 |
shstr &operator = (char const *rhs); |
| 94 |
shstr &operator = (const shstr &rhs); |
| 95 |
bool operator == (const shstr &rhs) const; |
| 96 |
bool operator != (const shstr &rhs) const; |
| 97 |
|
| 98 |
friend std::ostream &operator << (std::ostream &os, const shstr &str) |
| 99 |
{ |
| 100 |
os << str.m_str; |
| 101 |
return os; |
| 102 |
} |
| 103 |
|
| 104 |
protected: |
| 105 |
char const *m_str; |
| 106 |
size_type m_len; |
| 107 |
|
| 108 |
void erase () |
| 109 |
{ |
| 110 |
erase (m_str); |
| 111 |
m_str = NULL; |
| 112 |
} |
| 113 |
|
| 114 |
void insert (char const *newstr) |
| 115 |
{ |
| 116 |
m_str = insert (newstr, &m_len); |
| 117 |
} |
| 118 |
}; |
| 119 |
|
| 120 |
#endif // SHSTR_H |