1 /* GemRB - Infinity Engine Emulator
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
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
33 LRUCache::LRUCache() : v(), head(0), tail(0) {
34 v
.SetType(GEM_VARIABLES_POINTER
);
43 int LRUCache::GetCount() const
48 void LRUCache::SetAt(const char* key
, void* value
)
51 if (v
.Lookup(key
, p
)) {
52 VarEntry
* e
= (VarEntry
*) p
;
58 VarEntry
* e
= new VarEntry();
62 e
->key
= new char[strlen(key
)+1];
68 if (tail
== 0) tail
= head
;
70 v
.SetAt(key
, (void*)e
);
73 bool LRUCache::Lookup(const char* key
, void*& value
) const
76 if (v
.Lookup(key
, p
)) {
77 VarEntry
* e
= (VarEntry
*) p
;
84 bool LRUCache::Touch(const char* key
)
87 if (!v
.Lookup(key
, p
)) return false;
88 VarEntry
* e
= (VarEntry
*) p
;
91 if (!e
->prev
) return true;
100 if (tail
== 0) tail
= head
;
104 bool LRUCache::Remove(const char* key
)
107 if (!v
.Lookup(key
, p
)) return false;
108 VarEntry
* e
= (VarEntry
*) p
;
116 bool LRUCache::getLRU(unsigned int n
, const char*& key
, void*& value
) const
119 for (unsigned int i
= 0; i
< n
; ++i
) {
120 if (!e
) return false;
123 if (!e
) return false;
130 void LRUCache::removeFromList(VarEntry
* e
)
134 e
->prev
->next
= e
->next
;
142 e
->next
->prev
= e
->prev
;
148 e
->prev
= e
->next
= 0;
158 for (i
= 0; i
< 100; ++i
) t
[i
] = 1000+i
;
160 for (i
= 0; i
< 100; ++i
) {
162 sprintf(k
[i
], "k%03d", i
);
169 r
= c
.Lookup("k050", p
);
172 c
.SetAt("k050", &t
[50]);
173 r
= c
.Lookup("k050", p
);
177 for (i
= 0; i
< 100; ++i
)
178 c
.SetAt(k
[i
], &t
[i
]);
180 r
= c
.getLRU(0, k2
, p
);
182 assert(strcmp(k2
, "k000") == 0);
186 r
= c
.getLRU(0, k2
, p
);
188 assert(strcmp(k2
, "k001") == 0);
191 r
= c
.getLRU(1, k2
, p
);
193 assert(strcmp(k2
, "k002") == 0);
198 r
= c
.getLRU(0, k2
, p
);
200 assert(strcmp(k2
, "k002") == 0);
203 for (i
= 0; i
< 98; ++i
) {
204 r
= c
.getLRU(0, k2
, p
);
206 assert(strcmp(k2
, k
[2+i
]) == 0);
207 assert(p
== &t
[2+i
]);
211 assert(c
.GetCount() == 1);
213 r
= c
.getLRU(0, k2
, p
);
215 assert(strcmp(k2
, "k000") == 0);
218 assert(!c
.getLRU(1, k2
, p
));