summaryrefslogtreecommitdiff
path: root/cpp/src/IceGrid/Cache.h
diff options
context:
space:
mode:
Diffstat (limited to 'cpp/src/IceGrid/Cache.h')
-rw-r--r--cpp/src/IceGrid/Cache.h150
1 files changed, 150 insertions, 0 deletions
diff --git a/cpp/src/IceGrid/Cache.h b/cpp/src/IceGrid/Cache.h
new file mode 100644
index 00000000000..da799248a0f
--- /dev/null
+++ b/cpp/src/IceGrid/Cache.h
@@ -0,0 +1,150 @@
+// **********************************************************************
+//
+// Copyright (c) 2003-2005 ZeroC, Inc. All rights reserved.
+//
+// This copy of Ice is licensed to you under the terms described in the
+// ICE_LICENSE file included in this distribution.
+//
+// **********************************************************************
+
+#ifndef ICE_GRID_CACHE_H
+#define ICE_GRID_CACHE_H
+
+#include <IceUtil/Mutex.h>
+#include <IceUtil/Shared.h>
+#include <IceGrid/Util.h>
+
+namespace IceGrid
+{
+
+class Database;
+
+template<typename Key, typename Value>
+class Cache : public IceUtil::Mutex
+{
+ typedef IceUtil::Handle<Value> ValuePtr;
+
+public:
+
+ Cache() : _entriesHint(_entries.end())
+ {
+ }
+
+ virtual
+ ~Cache()
+ {
+ }
+
+ virtual bool
+ has(const Key& key)
+ {
+ Lock sync(*this);
+ return getImpl(key);
+ }
+
+ virtual ValuePtr
+ remove(const Key& key)
+ {
+ Lock sync(*this);
+ return removeImpl(key);
+ }
+
+protected:
+
+ ValuePtr
+ getImpl(const Key& key, bool create = false)
+ {
+ typename std::map<Key, ValuePtr>::iterator p = _entries.end();
+ if(_entriesHint != _entries.end())
+ {
+ if(_entriesHint->first == key)
+ {
+ p = _entriesHint;
+ }
+ }
+
+ if(p == _entries.end())
+ {
+ p = _entries.find(key);
+ }
+
+ if(p != _entries.end())
+ {
+ _entriesHint = p;
+ return p->second;
+ }
+ else
+ {
+ if(create)
+ {
+ ValuePtr entry = createEntry(key);
+ _entriesHint = _entries.insert(_entriesHint, make_pair(key, entry));
+ return entry;
+ }
+ else
+ {
+ return 0;
+ }
+ }
+ }
+
+ ValuePtr
+ removeImpl(const Key& key)
+ {
+ typename std::map<Key, ValuePtr>::iterator p = _entries.end();
+ if(_entriesHint != _entries.end())
+ {
+ if(_entriesHint->first == key)
+ {
+ p = _entriesHint;
+ }
+ }
+
+ if(p == _entries.end())
+ {
+ p = _entries.find(key);
+ }
+
+ assert(p != _entries.end());
+ if(p->second->canRemove())
+ {
+ ValuePtr entry = p->second;
+ _entries.erase(p);
+ _entriesHint = _entries.end();
+ return entry;
+ }
+ else
+ {
+ _entriesHint = p;
+ return p->second;
+ }
+ }
+
+ virtual ValuePtr
+ createEntry(const Key& key)
+ {
+ return new Value(*this, key);
+ }
+
+ std::map<Key, ValuePtr> _entries;
+ typename std::map<Key, ValuePtr>::iterator _entriesHint;
+};
+
+template<typename T>
+class CacheByString : public Cache<std::string, T>
+{
+ typedef IceUtil::Handle<T> TPtr;
+
+public:
+
+ virtual std::vector<std::string>
+ getAll(const std::string& expr)
+ {
+ IceUtil::Mutex::Lock sync(*this);
+ return getMatchingKeys<std::map<std::string,TPtr> >(_entries, expr);
+ }
+};
+
+};
+
+#endif