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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
/*
* Worldvisions Weaver Software:
* Copyright (C) 2005 Net Integration Technologies, Inc.
*
* Definition for the WvStringCache class. See wvstringcache.h.
*/
#include "wvstringcache.h"
#include "wvstringlist.h"
WvStringTable *WvStringCache::t;
int WvStringCache::refcount;
size_t WvStringCache::clean_threshold;
WvStringCache::WvStringCache()
{
refcount++;
if (!t)
{
t = new WvStringTable;
clean_threshold = 0;
}
}
WvStringCache::~WvStringCache()
{
refcount--;
if (!refcount)
{
delete t;
t = NULL;
clean_threshold = 0;
}
else
clean();
}
WvString WvStringCache::get(WvStringParm s)
{
// return s; // disable cache
WvString *ret = (*t)[s];
if (ret)
{
// printf("found(%s)\n", s.cstr());
return *ret;
}
else
{
// printf(" new(%s)\n", s.cstr());
ret = new WvString(s);
t->add(ret, true);
return *ret;
}
}
void WvStringCache::clean()
{
// do we actually need to clean yet? Skip it if we haven't added too
// many items since the last clean, since cleaning is pretty slow.
if (t->count() < clean_threshold)
return;
WvStringList l;
// use a two-stage process so the iterator doesn't get messed up
// FIXME: this might actually be unnecessary with WvScatterHash, but
// someone should actually confirm that before taking this out.
{
WvStringTable::Iter i(*t);
for (i.rewind(); i.next(); )
{
if (i->is_unique()) // last remaining instance
{
// printf("CLEANUP(%s)\n", i->cstr());
l.append(i.ptr(), false);
}
}
}
// printf("CLEANUP-1: %d elements at start (%d to remove)\n",
// (int)t->count(), (int)l.count());
{
WvStringList::Iter i(l);
for (i.rewind(); i.next(); )
t->remove(i.ptr());
}
clean_threshold = t->count() + t->count()/10 + 1;
// printf("CLEANUP-2: %d elements left (thres=%d).\n",
// (int)t->count(), (int)clean_threshold);
}
|