forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CuckooHashTable.cs
367 lines (302 loc) · 11.4 KB
/
CuckooHashTable.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/***
* Cuckoo Hash Table.
*
* A hash table that implements the Cuckoo Hashing algorithm for resolving keys-collisions.
* This is a single-table implementation, the source behind this idea is the work of Mark Allen Weiss, 2014.
*/
using System;
using System.Collections.Generic;
using DataStructures.Common;
using DataStructures.Hashing;
using System.Threading.Tasks;
namespace DataStructures.Dictionaries
{
/// <summary>
/// THE CUCKOO HASH TABLE Data Structure.
/// </summary>
public class CuckooHashTable<TKey, TValue> where TKey : IComparable<TKey>
{
/// <summary>
/// THE CUCKOO HASH TABLE ENTERY
/// </summary>
private class CHashEntry<TKey, TValue> where TKey : IComparable<TKey>
{
public TKey Key { get; set; }
public TValue Value { get; set; }
public bool IsActive { get; set; }
public CHashEntry() : this(default(TKey), default(TValue), false) { }
public CHashEntry(TKey key, TValue value, bool isActive)
{
Key = key;
Value = value;
IsActive = isActive;
}
}
/// <summary>
/// INSTANCE VARIABLES
/// </summary>
private const int DEFAULT_CAPACITY = 11;
private const double MAX_LOAD_FACTOR = 0.45;
private const int ALLOWED_REHASHES = 5;
private const int NUMBER_OF_HASH_FUNCTIONS = 7; // number of hash functions to use, selected 7 because it's prime. The choice was arbitrary.
internal readonly PrimesList PRIMES = PrimesList.Instance;
// Random number generator
private Random _randomizer;
private int _size { get; set; }
private int _numberOfRehashes { get; set; }
private CHashEntry<TKey, TValue>[] _collection { get; set; }
private UniversalHashingFamily _universalHashingFamily { get; set; }
private EqualityComparer<TKey> _equalityComparer = EqualityComparer<TKey>.Default;
// The C# Maximum Array Length (before encountering overflow)
// Reference: http://referencesource.microsoft.com/#mscorlib/system/array.cs,2d2b551eabe74985
private const int MAX_ARRAY_LENGTH = 0X7FEFFFFF;
/// <summary>
/// CONSTRUCTOR
/// </summary>
public CuckooHashTable()
{
_size = 0;
_numberOfRehashes = 0;
_randomizer = new Random();
_collection = new CHashEntry<TKey, TValue>[DEFAULT_CAPACITY];
_universalHashingFamily = new UniversalHashingFamily(NUMBER_OF_HASH_FUNCTIONS);
}
/// <summary>
/// Expands the size of internal collection.
/// </summary>
private void _expandCapacity(int minCapacity)
{
int newCapacity = (_collection.Length == 0 ? DEFAULT_CAPACITY : _collection.Length * 2);
// Handle overflow
if (newCapacity >= MAX_ARRAY_LENGTH)
newCapacity = MAX_ARRAY_LENGTH;
else if (newCapacity < minCapacity)
newCapacity = minCapacity;
_rehash(Convert.ToInt32(newCapacity));
}
/// <summary>
/// Contracts the size of internal collection to half.
/// </summary>
private void _contractCapacity()
{
_rehash(_size / 2);
}
/// <summary>
/// Rehashes the internal internal collection.
/// Table size stays the same, but generates new hash functions.
/// </summary>
private void _rehash()
{
_universalHashingFamily.GenerateNewFunctions();
_rehash(_collection.Length);
}
/// <summary>
/// Rehashes the internal collection to a new size.
/// New hash table size, but the hash functions stay the same.
/// </summary>
private void _rehash(int newCapacity)
{
int primeCapacity = PRIMES.GetNextPrime(newCapacity);
var oldSize = _size;
var oldCollection = this._collection;
try
{
this._collection = new CHashEntry<TKey, TValue>[newCapacity];
// Reset size
_size = 0;
for (int i = 0; i < oldCollection.Length; ++i)
{
if (oldCollection[i] != null && oldCollection[i].IsActive == true)
{
_insertHelper(oldCollection[i].Key, oldCollection[i].Value);
}
}
}
catch (OutOfMemoryException ex)
{
// In case a memory overflow happens, return the data to it's old state
// ... then throw the exception.
_collection = oldCollection;
_size = oldSize;
throw ex.InnerException;
}
}
/// <summary>
/// Hashes a key, using the specified hash function number which belongs to the internal hash functions family.
/// </summary>
private int _cuckooHash(TKey key, int whichHashFunction)
{
if (whichHashFunction <= 0 || whichHashFunction > _universalHashingFamily.NumberOfFunctions)
throw new ArgumentOutOfRangeException("Which Hash Function parameter must be betwwen 1 and " + NUMBER_OF_HASH_FUNCTIONS + ".");
int hashCode = Math.Abs(_universalHashingFamily.UniversalHash(_equalityComparer.GetHashCode(key), whichHashFunction));
return hashCode % _collection.Length;
}
/// <summary>
/// Checks whether there is an entry at the specified position and that the entry is active.
/// </summary>
private bool _isActive(int index)
{
if (index < 0 || index > _collection.Length)
throw new IndexOutOfRangeException();
return (_collection[index] != null && _collection[index].IsActive == true);
}
/// <summary>
/// Returns the array position (index) of the specified key.
/// </summary>
private int _findPosition(TKey key)
{
// The hash functions numbers are indexed from 1 not zero
for (int i = 1; i <= NUMBER_OF_HASH_FUNCTIONS; ++i)
{
int index = _cuckooHash(key, i);
if (_isActive(index) && _collection[index].Key.IsEqualTo(key))
return index;
}
return -1;
}
/// <summary>
/// Inserts a key-value pair into hash table.
/// </summary>
private void _insertHelper(TKey key, TValue value)
{
int COUNT_LIMIT = 100;
var newEntry = new CHashEntry<TKey, TValue>(key, value, isActive: true);
while (true)
{
int position, lastPosition = -1;
for (int count = 0; count < COUNT_LIMIT; count++)
{
// The hash functions numbers are indexed from 1 not zero
for (int i = 1; i <= NUMBER_OF_HASH_FUNCTIONS; i++)
{
position = _cuckooHash(key, i);
if (!_isActive(position))
{
_collection[position] = newEntry;
// Increment size
++_size;
return;
}
}
// Eviction strategy:
// No available spot was found. Choose a random one.
int j = 0;
do
{
position = _cuckooHash(key, _randomizer.Next(1, NUMBER_OF_HASH_FUNCTIONS));
} while (position == lastPosition && j++ < NUMBER_OF_HASH_FUNCTIONS);
// SWAP ENTRY
lastPosition = position;
var temp = _collection[position];
_collection[position] = newEntry;
newEntry = temp;
}//end-for
if (++_numberOfRehashes > ALLOWED_REHASHES)
{
// Expand the table.
_expandCapacity(_collection.Length + 1);
// Reset number of rehashes.
_numberOfRehashes = 0;
}
else
{
// Rehash the table with the same current size.
_rehash();
}
}//end-while
}
/// <summary>
/// Returns number of items in hash table.
/// </summary>
/// <returns></returns>
public int Count()
{
return _size;
}
/// <summary>
/// Returns true if hash table is empty; otherwise, false.
/// </summary>
public bool IsEmpty()
{
return (_size == 0);
}
/// <summary>
/// Returns the value of the specified key, if exists; otherwise, raises an exception.
/// </summary>
public TValue this[TKey key]
{
get
{
int position = _findPosition(key);
if (position != -1)
return _collection[position].Value;
throw new KeyNotFoundException();
}
set
{
if (ContainsKey(key) == true)
Update(key, value);
throw new KeyNotFoundException();
}
}
/// <summary>
/// Checks if a key exists in the hash table.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool ContainsKey(TKey key)
{
return (_findPosition(key) != -1);
}
/// <summary>
/// Insert key-value pair into hash table.
/// </summary>
public void Add(TKey key, TValue value)
{
if (ContainsKey(key))
throw new Exception("Key already exists in the hash table.");
if (_size >= _collection.Length * MAX_LOAD_FACTOR)
_expandCapacity(_collection.Length + 1);
_insertHelper(key, value);
}
/// <summary>
/// Updates a key-value pair with a new value.
/// </summary>
public void Update(TKey key, TValue value)
{
int position = _findPosition(key);
if (position == -1)
throw new KeyNotFoundException();
_collection[position].Value = value;
}
/// <summary>
/// Remove the key-value pair specified by the given key.
/// </summary>
public bool Remove(TKey key)
{
int currentPosition = _findPosition(key);
if (!_isActive(currentPosition))
return false;
// Mark the entry as not active
_collection[currentPosition].IsActive = false;
// Decrease the size
--_size;
return true;
}
/// <summary>
/// Clears this hash table.
/// </summary>
public void Clear()
{
this._size = 0;
Parallel.ForEach(_collection,
(item) =>
{
if (item != null && item.IsActive == true)
{
item.IsActive = false;
}
});
}
}
}