File: string_pool.hh

package info (click to toggle)
jlint 3.0-4.2
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 776 kB
  • ctags: 662
  • sloc: cpp: 5,837; ansic: 1,496; makefile: 299; perl: 93; sh: 49
file content (77 lines) | stat: -rw-r--r-- 1,623 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#ifndef STRING_POOL_HH
#define STRING_POOL_HH

#include <cstdlib>
#include <cstring>

#ifdef __GNUC__
#if __GNUC__ > 2
using namespace std;
#endif
#endif


/******************************************************************************/
/* Class that allocates a const char* if not yet present in string pool       */
/******************************************************************************/

// table of all locks a thread is holding
#ifdef HASH_TABLE
#include <hash_set>
#else
#include <set>
#endif
#ifdef HASH_TABLE
struct eqstr
{
  bool operator()(const char* s1, const char* s2) const
  {
    return strcmp(s1, s2) == 0;
  }
};
typedef hash_set<const char*, hash<const char*>, eqstr> string_table;
#else
struct ltstr
{
  bool operator()(const char* s1, const char* s2) const
  {
    return strcmp(s1, s2) < 0;
  }
};
typedef set<const char*, ltstr> string_table;
#endif

class string_pool {
public:
  string_table pool;

  const char* add(const char* el) {
    char* entry;
    string_table::iterator it;
    if ((it = pool.find(el)) == pool.end()) {
      // allocate element!
      entry = strdup(el);
      pool.insert(entry);
      return const_cast<const char*>(entry);
    } else {
      return *it;
    }
  }

  void remove(const char* el) {
    string_table::iterator entry;
    if ((entry = pool.find(el)) != pool.end()) {
      // free space for element
      free(const_cast<char*>(*entry));
      pool.erase(entry);
    }
  }

  void clear() {
    for (string_table::iterator it = pool.begin(); it != pool.end(); it++) {
      free(const_cast<char*>(*it));
      pool.erase(it);
    }
  }
};
#endif