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