2 * Copyright 2005, Haiku.
3 * Distributed under the terms of the MIT License.
6 * Axel Dörfler, axeld@pinc-software.de
10 #include "HashTable.h"
20 struct HashTable::entry
{
26 HashTable::HashTable(bool owning
, int32 capacity
, float loadFactor
)
35 if (loadFactor
<= 0.3)
38 fLoadFactor
= loadFactor
;
43 HashTable::~HashTable()
50 HashTable::MakeEmpty(bool deleteValues
)
55 for (int32 index
= fCapacity
; --index
>= 0;) {
56 struct entry
*entry
, *next
;
58 for (entry
= fTable
[index
]; entry
!= NULL
; entry
= next
) {
73 HashTable::GetValue(Hashable
& key
) const
75 struct entry
* entry
= _GetHashEntry(key
);
77 return entry
!= NULL
? entry
->value
: NULL
;
82 HashTable::AddItem(Hashable
*value
)
84 struct entry
*entry
= _GetHashEntry(*value
);
85 int32 hash
= value
->Hash();
92 if (fCount
>= fThreshold
)
95 index
= hash
% fCapacity
;
97 entry
= new (nothrow
) HashTable::entry
;
101 entry
->value
= value
;
102 entry
->next
= fTable
[index
];
103 fTable
[index
] = entry
;
110 HashTable::RemoveItem(Hashable
& key
)
112 struct entry
* previous
= NULL
;
121 index
= hash
% fCapacity
;
123 for (entry
= fTable
[index
]; entry
!= NULL
; entry
= entry
->next
) {
124 if (entry
->value
->Hash() == hash
&& entry
->value
->CompareTo(key
)) {
125 // found value in array
129 previous
->next
= entry
->next
;
131 fTable
[index
] = entry
->next
;
134 value
= entry
->value
;
148 struct entry
** newTable
;
149 int32 oldCapacity
= fCapacity
;
150 int32 newCapacity
, i
;
153 newCapacity
= oldCapacity
* 2 + 1;
155 newCapacity
= fCapacity
;
157 newTable
= (struct entry
**)malloc(newCapacity
* sizeof(struct entry
*));
158 if (newTable
== NULL
)
161 memset(newTable
, 0, newCapacity
* sizeof(struct entry
*));
163 if (fTable
!= NULL
) {
164 // repopulate the entries into the new array
165 for (i
= fCapacity
; i
-- > 0;) {
169 for (entry
= fTable
[i
]; entry
!= NULL
; entry
= next
) {
172 int32 index
= entry
->value
->Hash() % newCapacity
;
173 entry
->next
= newTable
[index
];
174 newTable
[index
] = entry
;
182 fCapacity
= newCapacity
;
183 fThreshold
= int32(newCapacity
* fLoadFactor
);
189 struct HashTable::entry
*
190 HashTable::_GetHashEntry(Hashable
& key
) const
193 uint32 hash
= key
.Hash();
198 for (entry
= fTable
[hash
% fCapacity
]; entry
!= NULL
; entry
= entry
->next
) {
199 if (entry
->value
->Hash() == hash
&& entry
->value
->CompareTo(key
))