1/*
2 * Copyright 2011, Ingo Weinhold, ingo_weinhold@gmx.de.
3 * Distributed under the terms of the MIT License.
4 */
5#ifndef INDEX_H
6#define INDEX_H
7
8
9#include <string.h>
10
11#include <SupportDefs.h>
12
13#include <util/khash.h>
14#include <util/OpenHashTable.h>
15
16
17class AbstractIndexIterator;
18class IndexIterator;
19class Node;
20class Volume;
21
22
23static const size_t kMaxIndexKeyLength = 256;
24
25
26class Index {
27public:
28								Index();
29	virtual						~Index();
30
31			status_t			Init(Volume* volume, const char* name,
32									uint32 type, bool fixedKeyLength,
33									size_t keyLength = 0);
34
35			Volume*				GetVolume() const		{ return fVolume; }
36
37			const char*			Name() const			{ return fName; }
38			uint32				Type() const			{ return fType; }
39			bool				HasFixedKeyLength() const
40									{ return fFixedKeyLength; }
41			size_t				KeyLength() const		{ return fKeyLength; }
42
43	virtual	int32				CountEntries() const = 0;
44
45			bool				GetIterator(IndexIterator& iterator);
46			bool				Find(const void* key, size_t length,
47									IndexIterator& iterator);
48									// sets the iterator to the first value
49									// >= key
50
51			Index*&				IndexHashLink()
52									{ return fHashLink; }
53
54			// debugging
55			void				Dump();
56
57protected:
58	virtual	AbstractIndexIterator* InternalGetIterator() = 0;
59	virtual	AbstractIndexIterator* InternalFind(const void* key,
60									size_t length) = 0;
61									// returns an iterator pointing to the first
62									// value >= key
63
64protected:
65			Index*				fHashLink;
66			Volume*				fVolume;
67			char*				fName;
68			uint32				fType;
69			size_t				fKeyLength;
70			bool				fFixedKeyLength;
71};
72
73
74class IndexIterator {
75public:
76								IndexIterator();
77								~IndexIterator();
78
79			bool				HasNext() const;
80			Node*				Next();
81			Node*				Next(void* buffer, size_t* _keyLength);
82
83			status_t			Suspend();
84			status_t			Resume();
85
86private:
87			void				SetIterator(AbstractIndexIterator* iterator);
88
89private:
90			friend class Index;
91
92private:
93			AbstractIndexIterator* fIterator;
94};
95
96
97// #pragma mark - IndexHashDefinition
98
99
100struct IndexHashDefinition {
101	typedef const char*	KeyType;
102	typedef	Index		ValueType;
103
104	size_t HashKey(const char* key) const
105	{
106		return key != NULL ? hash_hash_string(key) : 0;
107	}
108
109	size_t Hash(const Index* value) const
110	{
111		return HashKey(value->Name());
112	}
113
114	bool Compare(const char* key, const Index* value) const
115	{
116		return strcmp(value->Name(), key) == 0;
117	}
118
119	Index*& GetLink(Index* value) const
120	{
121		return value->IndexHashLink();
122	}
123};
124
125
126typedef BOpenHashTable<IndexHashDefinition> IndexHashTable;
127
128
129#endif	// INDEX_H
130