3 /* Cache - a template cache class
5 ** Copyright 2001 pinc Software. All Rights Reserved.
6 ** Released under the terms of the MIT license.
10 #include <SupportDefs.h>
15 template<class T
> class Cache
32 // perform your "undirty" work here
35 virtual bool Equals(T
) = 0;
37 Cacheable
*prev
,*next
;
48 fMostRecentlyUsed(NULL
),
49 fLeastRecentlyUsed(NULL
)
58 void Clear(int32 targetCount
= 0,bool force
= false)
60 Cacheable
*entry
= fLeastRecentlyUsed
;
63 Cacheable
*prev
= entry
->prev
;
64 if (entry
->locked
<= 0 || force
)
67 entry
->next
->prev
= prev
;
69 prev
->next
= entry
->next
;
71 if (fLeastRecentlyUsed
== entry
)
72 fLeastRecentlyUsed
= prev
;
73 if (fMostRecentlyUsed
== entry
)
74 fMostRecentlyUsed
= prev
;
78 if (--fCount
<= targetCount
)
86 void SetHoldChanges(bool hold
)
93 status_t
SetDirty(T data
,bool dirty
)
95 Cacheable
*entry
= Get(data
);
97 return B_ENTRY_NOT_FOUND
;
99 entry
->isDirty
= dirty
;
103 status_t
Lock(T data
)
105 Cacheable
*entry
= Get(data
);
107 return B_ENTRY_NOT_FOUND
;
113 status_t
Unlock(T data
)
115 Cacheable
*entry
= Get(data
);
117 return B_ENTRY_NOT_FOUND
;
123 Cacheable
*Get(T data
)
125 Cacheable
*entry
= GetFromCache(data
);
128 if (fMostRecentlyUsed
== entry
)
131 // remove entry from cache (to insert it at top of the MRU list)
133 entry
->prev
->next
= entry
->next
;
136 if (fLeastRecentlyUsed
== entry
)
137 fLeastRecentlyUsed
= entry
->prev
;
139 fprintf(stderr
,"Cache: fatal error, fLeastRecentlyUsed != entry\n");
142 entry
->next
->prev
= entry
->prev
;
146 entry
= NewCacheable(data
);
153 // insert entry at the top of the MRU list
154 entry
->next
= fMostRecentlyUsed
;
157 if (fMostRecentlyUsed
)
158 fMostRecentlyUsed
->prev
= entry
;
159 else if (fLeastRecentlyUsed
== NULL
)
160 fLeastRecentlyUsed
= entry
;
162 fprintf(stderr
,"Cache: fatal error, fLeastRecently != NULL!\n");
163 fMostRecentlyUsed
= entry
;
165 // remove old nodes from of the cache (if possible and necessary)
167 && fCount
> fMaxInQueue
168 && fLeastRecentlyUsed
)
175 Cacheable
*GetFromCache(T data
)
177 Cacheable
*entry
= fMostRecentlyUsed
;
180 if (entry
->Equals(data
))
187 virtual Cacheable
*NewCacheable(T data
) = 0;
189 int32 fMaxInQueue
, fCount
;
191 Cacheable
*fMostRecentlyUsed
;
192 Cacheable
*fLeastRecentlyUsed
;