00001
00002
00003
00004 #ifndef __ug_tsa_bitset_cache_h
00005 #define __ug_tsa_bitset_cache_h
00006
00007 #include <map>
00008 #include <boost/shared_ptr.hpp>
00009 #include <boost/dynamic_bitset.hpp>
00010 #include <stdint.h>
00011 #include <iostream>
00012
00013
00014
00015
00016
00017
00018
00019 namespace sapt
00020 {
00021
00022 template<typename TSA>
00023 class
00024 BitSetCache
00025 {
00026 public:
00027 typedef boost::dynamic_bitset<uint64_t> BitSet;
00028 typedef boost::shared_ptr<BitSet> bsptr;
00029 typedef std::map<std::pair<char const*,ushort>,bsptr> myMap;
00030 typedef myMap::iterator myMapIter;
00031 private:
00032 TSA const* tsa;
00033 myMap cached1,cached2;
00034 int threshold;
00035 public:
00036
00037 BitSetCache() : tsa(NULL), threshold(0) {};
00038 BitSetCache(TSA const* t, size_t th=4194304)
00039 {
00040 init(t,th);
00041 };
00042
00043 void
00044 init(TSA const* t, size_t th=4194304)
00045 {
00046 tsa = t;
00047 threshold = th;
00048 }
00049
00050 bsptr
00051 get(typename TSA::Token const* keyStart, size_t keyLen)
00052 {
00053 bsptr ret;
00054 char const* lo = tsa->lower_bound(keyStart,keyLen);
00055 char const* up = tsa->upper_bound(keyStart,keyLen);
00056 if (!lo) return ret;
00057 if (up-lo > threshold)
00058 {
00059 std::pair<char const*,ushort> k(lo,keyLen);
00060 myMapIter m = cached1.find(k);
00061 if (m != cached1.end())
00062 ret = m->second;
00063 else
00064 {
00065 ret.reset(new BitSet(tsa->getCorpus()->size()));
00066 cached1[k] = ret;
00067 }
00068 }
00069 else if (ret == NULL)
00070 ret.reset(new BitSet(tsa->getCorpus()->size()));
00071 if (ret->count() == 0)
00072 tsa->setBits(lo,up,*ret);
00073 return ret;
00074 }
00075
00076
00077 bsptr
00078 get2(typename TSA::Token const* keyStart, size_t keyLen, bool onlyEndpoint=true)
00079 {
00080 bsptr ret;
00081 char const* lo = tsa->lower_bound(keyStart,keyLen);
00082 char const* up = tsa->upper_bound(keyStart,keyLen);
00083 if (!lo) return ret;
00084 if (up-lo > threshold)
00085 {
00086 std::pair<char const*,ushort> k(lo,keyLen);
00087
00088
00089 myMapIter m = cached2.find(k);
00090 if (m != cached2.end())
00091 ret = m->second;
00092 else
00093 {
00094 ret.reset(new BitSet(tsa->getCorpus()->numTokens()));
00095 cached2[k] = ret;
00096 }
00097 }
00098 else if (ret == NULL)
00099 ret.reset(new BitSet(tsa->getCorpus()->numTokens()));
00100 if (ret->count() == 0)
00101 {
00102 if (onlyEndpoint)
00103 tsa->setTokenBits(lo,up,keyLen,*ret);
00104 else
00105 tsa->markOccurrences(lo,up,keyLen,*ret,false);
00106 }
00107 return ret;
00108 }
00109
00110 void clear()
00111 {
00112 cached1.clear();
00113 cached2.clear();
00114 }
00115
00116 };
00117 }
00118 #endif