1/*
2 * Copyright 2008, Axel D��rfler. All Rights Reserved.
3 * Copyright 2007, Hugo Santos. All Rights Reserved.
4 *
5 * Distributed under the terms of the MIT License.
6 */
7#ifndef HASHED_OBJECT_CACHE_H
8#define HASHED_OBJECT_CACHE_H
9
10
11#include <util/OpenHashTable.h>
12
13#include "ObjectCache.h"
14#include "slab_private.h"
15
16
17struct HashedSlab : slab {
18	HashedSlab*	hash_next;
19};
20
21
22struct HashedObjectCache : ObjectCache {
23								HashedObjectCache();
24
25	static	HashedObjectCache*	Create(const char* name, size_t object_size,
26									size_t alignment, size_t maximum,
27									size_t magazineCapacity,
28									size_t maxMagazineCount,
29									uint32 flags, void* cookie,
30									object_cache_constructor constructor,
31									object_cache_destructor destructor,
32									object_cache_reclaimer reclaimer);
33	virtual	void				Delete();
34
35	virtual	slab*				CreateSlab(uint32 flags);
36	virtual	void				ReturnSlab(slab* slab, uint32 flags);
37	virtual slab*				ObjectSlab(void* object) const;
38
39private:
40			struct Definition {
41				typedef HashedObjectCache	ParentType;
42				typedef const void*			KeyType;
43				typedef HashedSlab			ValueType;
44
45				Definition(HashedObjectCache* parent)
46					:
47					parent(parent)
48				{
49				}
50
51				Definition(const Definition& definition)
52					:
53					parent(definition.parent)
54				{
55				}
56
57				size_t HashKey(const void* key) const
58				{
59					return (addr_t)::lower_boundary(key, parent->slab_size)
60						>> parent->lower_boundary;
61				}
62
63				size_t Hash(HashedSlab* value) const
64				{
65					return HashKey(value->pages);
66				}
67
68				bool Compare(const void* key, HashedSlab* value) const
69				{
70					return value->pages == key;
71				}
72
73				HashedSlab*& GetLink(HashedSlab* value) const
74				{
75					return value->hash_next;
76				}
77
78				HashedObjectCache*	parent;
79			};
80
81			struct InternalAllocator {
82				void* Allocate(size_t size) const
83				{
84					return slab_internal_alloc(size, 0);
85				}
86
87				void Free(void* memory) const
88				{
89					slab_internal_free(memory, 0);
90				}
91			};
92
93			typedef BOpenHashTable<Definition, false, false,
94				InternalAllocator> HashTable;
95
96			friend struct Definition;
97
98private:
99			void				_ResizeHashTableIfNeeded(uint32 flags);
100
101private:
102			HashTable hash_table;
103			size_t lower_boundary;
104};
105
106
107
108#endif	// HASHED_OBJECT_CACHE_H
109