2
* Copyright (C) 2002,2003 Daniel Heck
4
* This program is free software; you can redistribute it and/or
5
* modify it under the terms of the GNU General Public License
6
* as published by the Free Software Foundation; either version 2
7
* of the License, or (at your option) any later version.
9
* This program is distributed in the hope that it will be useful,
10
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
* GNU General Public License for more details.
14
* You should have received a copy of the GNU General Public License along
15
* with this program; if not, write to the Free Software Foundation, Inc.,
16
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
18
* $Id: cache.hh,v 1.5 2004/04/24 11:46:01 dheck Exp $
23
/* -------------------- Cache -------------------- */
26
A generic class for caching external data. Stored data is owned by
27
the cache and is automatically `release'd on destruction. Missing
28
values are automatically retrieved using the `acquire' method.
36
class DeleteDisposer {
38
static void dispose (T p)
42
template <class T, class Disposer>
48
// ---------- Methods ----------
50
T get (const std::string &key);
51
void remove (const std::string &key);
52
unsigned size() const;
53
bool has_key(const std::string &key) const;
55
T store (const std::string &key, T value);
58
Cache (const Cache &other);
59
Cache &operator= (const Cache &other);
61
void release (T value) {
62
Disposer::dispose (value);
65
// ---------- Interface ----------
66
virtual T acquire (const std::string &name) = 0;
68
// ---------- Variables ----------
69
typedef px::Dict<T> Map;
70
typedef typename Map::iterator iterator;
75
template <class T, class D>
76
Cache<T,D>::Cache() : cache(1223) {
79
template <class T, class D>
80
void Cache<T, D>::clear() {
81
for (iterator i=cache.begin(); i!=cache.end(); ++i)
86
template <class T, class D>
87
void Cache<T, D>::remove (const std::string &key)
93
template <class T, class D>
94
T Cache<T,D>::store (const std::string &key, T value) {
95
cache.insert(key, value);
99
template <class T, class D>
100
T Cache<T,D>::get(const std::string &key) {
101
iterator i=cache.find(key);
105
return store (key, acquire(key));
108
template <class T, class D>
109
unsigned Cache<T,D>::size() const {
113
template <class T, class D>
114
bool Cache<T, D>::has_key(const std::string &key) const {
115
return cache.has_key(key);
118
/* -------------------- PtrCache -------------------- */
121
class PtrCache : public Cache<T*, DeleteDisposer<T*> > {
123
~PtrCache() { this->clear(); }
125
// void release (T *value) { delete value; }