summaryrefslogtreecommitdiff
path: root/src/cache.h
blob: f7b71ce208a2647e605a5f1d61fa0728e70dd895 (plain)
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
98
99
#ifndef BU_CACHE_H
#define BU_CACHE_H

#include "bu/cptr.h"
#include "bu/hash.h"
#include "bu/list.h"
#include "bu/cachehandler.h"

#define BU_TRACE
#include "bu/trace.h"

namespace Bu
{
	template<class obtype>
	class Cache
	{
	friend class Bu::CPtr<obtype>;
		typedef Bu::CPtr<obtype> Ptr;
		typedef Bu::CacheHandler<obtype> Handler;
		typedef Bu::List<Handler *> HandlerList;
	public:
		typedef long cid_t;	/**< Cache ID type. Unique cache entry ID. */

	public:
		Cache()
		{
			TRACE();
		}

		virtual ~Cache()
		{
			TRACE();
/*			for( HandlerList::iterator i = lHandler.begin();
				 i != lHandler.end(); i++ )
			{
				delete *i;
			}
*/		}

		void appendHandler( Handler *pHand )
		{
			lHandler.append( pHand );
		}

		void prependHandler( Handler *pHand )
		{
			lHandler.prepend( pHand );
		}

		Ptr insert( obtype *pData )
		{
			TRACE();
			CacheEntry e = {pData, 0};
			hEnt.insert( /*pData*/ 0 , e );
			return Ptr( *this, pData );
		}

		Ptr get( cid_t cId )
		{
			TRACE();
			return Ptr( *this, hEnt.get( cId ).pData );
		}

		int getRefCnt( cid_t cId )
		{
			TRACE();
			return hEnt.get( cId ).iRefs;
		}

	private:
		void incRef( cid_t cId )
		{
			TRACE();
			hEnt.get( cId ).iRefs++;
		}

		void decRef( cid_t cId )
		{
			TRACE();
			CacheEntry &e = hEnt.get( cId );
			e.iRefs--;
		}

	private:
		typedef struct CacheEntry
		{
			obtype *pData;
			int iRefs;
		} CacheEntry;

		//typedef Bu::Hash<ptrdiff_t, int> RefHash;
		typedef Bu::Hash<cid_t, CacheEntry> CidHash;
		//RefHash hRefs;
		CidHash hEnt;
		HandlerList lHandler;
	};
};

#endif