1 /* GemRB - Infinity Engine Emulator
2  * Copyright (C) 2003 |Avenger|
3  *
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.
8  *
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.
13  *
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.
17  *
18  *
19  */
20 
21 #ifndef CACHE_H
22 #define CACHE_H
23 
24 #include "globals.h"
25 
26 namespace GemRB {
27 
28 #define KEYSIZE 8
29 
30 #ifndef ReleaseFun
31 typedef void (*ReleaseFun)(void *);
32 #endif
33 
34 class Cache
35 {
36 protected:
37 	// Association
38 	struct MyAssoc {
39 		MyAssoc* pNext;
40 		MyAssoc** pPrev;
41 		char key[KEYSIZE]; //not ieResRef!
42 		ieDword nRefCount;
43 		void* data;
44 	};
45 	struct MemBlock {
46 		MemBlock* pNext;
47 	};
48 
49 public:
50 	// Construction
51 	Cache(int nBlockSize = 10, int nHashTableSize = 129);
52 
53 	// Attributes
54 	// number of elements
GetCount()55 	inline int GetCount() const
56 	{
57 		return m_nCount;
58 	}
IsEmpty()59 	inline bool IsEmpty() const
60 	{
61 		return m_nCount==0;
62 	}
63 	// Lookup
64 	void *GetResource(const ieResRef key) const;
65 	// Operations
66 	bool SetAt(const ieResRef key, void *rValue);
67 	// decreases refcount or drops data
68 	//if name is supplied it is faster, it will use rValue to validate the request
69 	int DecRef(void *rValue, const ieResRef name, bool free);
70 	int RefCount(const ieResRef key) const;
71 	void RemoveAll(ReleaseFun fun);//removes all refcounts
72 	void Cleanup();  //removes only zero refcounts
73 	void InitHashTable(unsigned int hashSize, bool bAllocNow = true);
74 
75 	// Implementation
76 protected:
77 	MyAssoc** m_pHashTable;
78 	unsigned int m_nHashTableSize;
79 	int m_nCount;
80 	MyAssoc* m_pFreeList;
81 	MemBlock* m_pBlocks;
82 	int m_nBlockSize;
83 
84 	Cache::MyAssoc* NewAssoc();
85 	void FreeAssoc(Cache::MyAssoc*);
86 	Cache::MyAssoc* GetAssocAt(const ieResRef) const;
87 	Cache::MyAssoc *GetNextAssoc(Cache::MyAssoc * rNextPosition) const;
88 	unsigned int MyHashKey(const ieResRef) const;
89 
90 public:
91 	~Cache();
92 };
93 
94 }
95 
96 #endif //CACHE_H
97