WvStreams
wvstringcache.cc
1 /*
2  * Worldvisions Weaver Software:
3  * Copyright (C) 2005 Net Integration Technologies, Inc.
4  *
5  * Definition for the WvStringCache class. See wvstringcache.h.
6  */
7 #include "wvstringcache.h"
8 #include "wvstringlist.h"
9 
10 WvStringTable *WvStringCache::t;
11 int WvStringCache::refcount;
12 size_t WvStringCache::clean_threshold;
13 
14 WvStringCache::WvStringCache()
15 {
16  refcount++;
17  if (!t)
18  {
19  t = new WvStringTable;
20  clean_threshold = 0;
21  }
22 }
23 
24 
25 WvStringCache::~WvStringCache()
26 {
27  refcount--;
28  if (!refcount)
29  {
30  delete t;
31  t = NULL;
32  clean_threshold = 0;
33  }
34  else
35  clean();
36 }
37 
38 
40 {
41  // return s; // disable cache
42  WvString *ret = (*t)[s];
43  if (ret)
44  {
45  // printf("found(%s)\n", s.cstr());
46  return *ret;
47  }
48  else
49  {
50  // printf(" new(%s)\n", s.cstr());
51  ret = new WvString(s);
52  t->add(ret, true);
53  return *ret;
54  }
55 }
56 
57 
59 {
60  // do we actually need to clean yet? Skip it if we haven't added too
61  // many items since the last clean, since cleaning is pretty slow.
62  if (t->count() < clean_threshold)
63  return;
64 
65  WvStringList l;
66 
67  // use a two-stage process so the iterator doesn't get messed up
68  // FIXME: this might actually be unnecessary with WvScatterHash, but
69  // someone should actually confirm that before taking this out.
70  {
71  WvStringTable::Iter i(*t);
72  for (i.rewind(); i.next(); )
73  {
74  if (i->is_unique()) // last remaining instance
75  {
76  // printf("CLEANUP(%s)\n", i->cstr());
77  l.append(i.ptr(), false);
78  }
79  }
80  }
81 
82 // printf("CLEANUP-1: %d elements at start (%d to remove)\n",
83 // (int)t->count(), (int)l.count());
84 
85  {
86  WvStringList::Iter i(l);
87  for (i.rewind(); i.next(); )
88  t->remove(i.ptr());
89  }
90 
91  clean_threshold = t->count() + t->count()/10 + 1;
92 
93 // printf("CLEANUP-2: %d elements left (thres=%d).\n",
94 // (int)t->count(), (int)clean_threshold);
95 }
96 
97 
WvStringCache::get
WvString get(WvStringParm s)
Get a shared string corresponding to 's'.
Definition: wvstringcache.cc:39
WvStringTable
Definition: wvstringtable.h:17
WvString
WvString is an implementation of a simple and efficient printable-string class.
Definition: wvstring.h:329
WvStringList
This is a WvList of WvStrings, and is a really handy way to parse strings.
Definition: wvstringlist.h:27
WvStringCache::clean
void clean()
Remove any now-unused strings from the cache.
Definition: wvstringcache.cc:58