- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathCuckooHashTable.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.
*/
usingSystem;
usingSystem.Collections.Generic;
usingDataStructures.Common;
usingDataStructures.Hashing;
usingSystem.Threading.Tasks;
namespaceDataStructures.Dictionaries
{
/// <summary>
/// THE CUCKOO HASH TABLE Data Structure.
/// </summary>
publicclassCuckooHashTable<TKey,TValue>whereTKey:IComparable<TKey>
{
/// <summary>
/// THE CUCKOO HASH TABLE ENTERY
/// </summary>
privateclassCHashEntry<TKey,TValue>whereTKey:IComparable<TKey>
{
publicTKeyKey{get;set;}
publicTValueValue{get;set;}
publicboolIsActive{get;set;}
publicCHashEntry():this(default(TKey),default(TValue),false){}
publicCHashEntry(TKeykey,TValuevalue,boolisActive)
{
Key=key;
Value=value;
IsActive=isActive;
}
}
/// <summary>
/// INSTANCE VARIABLES
/// </summary>
privateconstintDEFAULT_CAPACITY=11;
privateconstdoubleMAX_LOAD_FACTOR=0.45;
privateconstintALLOWED_REHASHES=5;
privateconstintNUMBER_OF_HASH_FUNCTIONS=7;// number of hash functions to use, selected 7 because it's prime. The choice was arbitrary.
internalreadonlyPrimesListPRIMES=PrimesList.Instance;
// Random number generator
privateRandom_randomizer;
privateint_size{get;set;}
privateint_numberOfRehashes{get;set;}
privateCHashEntry<TKey,TValue>[]_collection{get;set;}
privateUniversalHashingFamily_universalHashingFamily{get;set;}
privateEqualityComparer<TKey>_equalityComparer=EqualityComparer<TKey>.Default;
// The C# Maximum Array Length (before encountering overflow)
// Reference: http://referencesource.microsoft.com/#mscorlib/system/array.cs,2d2b551eabe74985
privateconstintMAX_ARRAY_LENGTH=0X7FEFFFFF;
/// <summary>
/// CONSTRUCTOR
/// </summary>
publicCuckooHashTable()
{
_size=0;
_numberOfRehashes=0;
_randomizer=newRandom();
_collection=newCHashEntry<TKey,TValue>[DEFAULT_CAPACITY];
_universalHashingFamily=newUniversalHashingFamily(NUMBER_OF_HASH_FUNCTIONS);
}
/// <summary>
/// Expands the size of internal collection.
/// </summary>
privatevoid_expandCapacity(intminCapacity)
{
intnewCapacity=(_collection.Length==0?DEFAULT_CAPACITY:_collection.Length*2);
// Handle overflow
if(newCapacity>=MAX_ARRAY_LENGTH)
newCapacity=MAX_ARRAY_LENGTH;
elseif(newCapacity<minCapacity)
newCapacity=minCapacity;
_rehash(Convert.ToInt32(newCapacity));
}
/// <summary>
/// Contracts the size of internal collection to half.
/// </summary>
privatevoid_contractCapacity()
{
_rehash(_size/2);
}
/// <summary>
/// Rehashes the internal internal collection.
/// Table size stays the same, but generates new hash functions.
/// </summary>
privatevoid_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>
privatevoid_rehash(intnewCapacity)
{
intprimeCapacity=PRIMES.GetNextPrime(newCapacity);
varoldSize=_size;
varoldCollection=this._collection;
try
{
this._collection=newCHashEntry<TKey,TValue>[newCapacity];
// Reset size
_size=0;
for(inti=0;i<oldCollection.Length;++i)
{
if(oldCollection[i]!=null&&oldCollection[i].IsActive==true)
{
_insertHelper(oldCollection[i].Key,oldCollection[i].Value);
}
}
}
catch(OutOfMemoryExceptionex)
{
// In case a memory overflow happens, return the data to it's old state
// ... then throw the exception.
_collection=oldCollection;
_size=oldSize;
throwex.InnerException;
}
}
/// <summary>
/// Hashes a key, using the specified hash function number which belongs to the internal hash functions family.
/// </summary>
privateint_cuckooHash(TKeykey,intwhichHashFunction)
{
if(whichHashFunction<=0||whichHashFunction>_universalHashingFamily.NumberOfFunctions)
thrownewArgumentOutOfRangeException("Which Hash Function parameter must be betwwen 1 and "+NUMBER_OF_HASH_FUNCTIONS+".");
inthashCode=Math.Abs(_universalHashingFamily.UniversalHash(_equalityComparer.GetHashCode(key),whichHashFunction));
returnhashCode%_collection.Length;
}
/// <summary>
/// Checks whether there is an entry at the specified position and that the entry is active.
/// </summary>
privatebool_isActive(intindex)
{
if(index<0||index>_collection.Length)
thrownewIndexOutOfRangeException();
return(_collection[index]!=null&&_collection[index].IsActive==true);
}
/// <summary>
/// Returns the array position (index) of the specified key.
/// </summary>
privateint_findPosition(TKeykey)
{
// The hash functions numbers are indexed from 1 not zero
for(inti=1;i<=NUMBER_OF_HASH_FUNCTIONS;++i)
{
intindex=_cuckooHash(key,i);
if(_isActive(index)&&_collection[index].Key.IsEqualTo(key))
returnindex;
}
return-1;
}
/// <summary>
/// Inserts a key-value pair into hash table.
/// </summary>
privatevoid_insertHelper(TKeykey,TValuevalue)
{
intCOUNT_LIMIT=100;
varnewEntry=newCHashEntry<TKey,TValue>(key,value,isActive:true);
while(true)
{
intposition,lastPosition=-1;
for(intcount=0;count<COUNT_LIMIT;count++)
{
// The hash functions numbers are indexed from 1 not zero
for(inti=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.
intj=0;
do
{
position=_cuckooHash(key,_randomizer.Next(1,NUMBER_OF_HASH_FUNCTIONS));
}while(position==lastPosition&&j++<NUMBER_OF_HASH_FUNCTIONS);
// SWAP ENTRY
lastPosition=position;
vartemp=_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>
publicintCount()
{
return_size;
}
/// <summary>
/// Returns true if hash table is empty; otherwise, false.
/// </summary>
publicboolIsEmpty()
{
return(_size==0);
}
/// <summary>
/// Returns the value of the specified key, if exists; otherwise, raises an exception.
/// </summary>
publicTValuethis[TKeykey]
{
get
{
intposition=_findPosition(key);
if(position!=-1)
return_collection[position].Value;
thrownewKeyNotFoundException();
}
set
{
if(ContainsKey(key)==true)
Update(key,value);
thrownewKeyNotFoundException();
}
}
/// <summary>
/// Checks if a key exists in the hash table.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
publicboolContainsKey(TKeykey)
{
return(_findPosition(key)!=-1);
}
/// <summary>
/// Insert key-value pair into hash table.
/// </summary>
publicvoidAdd(TKeykey,TValuevalue)
{
if(ContainsKey(key))
thrownewException("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>
publicvoidUpdate(TKeykey,TValuevalue)
{
intposition=_findPosition(key);
if(position==-1)
thrownewKeyNotFoundException();
_collection[position].Value=value;
}
/// <summary>
/// Remove the key-value pair specified by the given key.
/// </summary>
publicboolRemove(TKeykey)
{
intcurrentPosition=_findPosition(key);
if(!_isActive(currentPosition))
returnfalse;
// Mark the entry as not active
_collection[currentPosition].IsActive=false;
// Decrease the size
--_size;
returntrue;
}
/// <summary>
/// Clears this hash table.
/// </summary>
publicvoidClear()
{
this._size=0;
Parallel.ForEach(_collection,
(item)=>
{
if(item!=null&&item.IsActive==true)
{
item.IsActive=false;
}
});
}
}
}