edits
[iotcloud.git] / version2 / src / C / hashtable.h
1 /*      Copyright (c) 2015 Regents of the University of California
2  *
3  *      Author: Brian Demsky <bdemsky@uci.edu>
4  *
5  *      This program is free software; you can redistribute it and/or
6  *      modify it under the terms of the GNU General Public License
7  *      version 2 as published by the Free Software Foundation.
8  */
9
10 /** @file hashtable.h
11  *  @brief Hashtable.  Standard chained bucket variety.
12  */
13
14 #ifndef HASHTABLE_H__
15 #define HASHTABLE_H__
16
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include "common.h"
21 #include "mymemory.h"
22
23 /**
24  * @brief Hashtable node
25  *
26  * @tparam _Key    Type name for the key
27  * @tparam _Val    Type name for the values to be stored
28  */
29 template<typename _Key, typename _Val>
30 struct Hashlistnode {
31         _Key key;
32         _Val val;
33         uint hashcode;
34 };
35
36 template<typename _Key, int _Shift, typename _KeyInt>
37 inline unsigned int defaultHashFunction(_Key hash) {
38         return (unsigned int)(((_KeyInt)hash) >> _Shift);
39 }
40
41 template<typename _Key>
42 inline bool defaultEquals(_Key key1, _Key key2) {
43         return key1 == key2;
44 }
45
46 /**
47  * @brief A simple, custom hash table
48  *
49  * By default it is snapshotting, but you can pass in your own allocation
50  * functions. Note that this table does not support the value 0 (NULL) used as
51  * a key and is designed primarily with pointer-based keys in mind. Other
52  * primitive key types are supported only for non-zero values.
53  *
54  * @tparam _Key    Type name for the key
55  * @tparam _Val    Type name for the values to be stored
56  * @tparam _KeyInt Integer type that is at least as large as _Key. Used for key
57  *                 manipulation and storage.
58  * @tparam _Shift  Logical shift to apply to all keys. Default 0.
59  */
60 template<typename _Key, typename _Val, typename _KeyInt, int _Shift = 0, unsigned int (*hash_function) (_Key) = defaultHashFunction<_Key, _Shift, _KeyInt>, bool (*equals) (_Key, _Key) = defaultEquals<_Key> >
61 class Hashtable {
62 public:
63         /**
64          * @brief Hash table constructor
65          * @param initialcapacity Sets the initial capacity of the hash table.
66          * Default size 1024.
67          * @param factor Sets the percentage full before the hashtable is
68          * resized. Default ratio 0.5.
69          */
70         Hashtable(unsigned int initialcapacity = 1024, double factor = 0.5) {
71                 // Allocate space for the hash table
72                 table = (struct Hashlistnode<_Key, _Val> *)ourcalloc(initialcapacity, sizeof(struct Hashlistnode<_Key, _Val>));
73                 zero = NULL;
74                 loadfactor = factor;
75                 capacity = initialcapacity;
76                 capacitymask = initialcapacity - 1;
77
78                 threshold = (unsigned int)(initialcapacity * loadfactor);
79                 size = 0;                                                       // Initial number of elements in the hash
80         }
81
82         /** @brief Hash table destructor */
83         ~Hashtable() {
84                 ourfree(table);
85                 if (zero)
86                         ourfree(zero);
87         }
88
89         /** Override: new operator */
90         void *operator new(size_t size) {
91                 return ourmalloc(size);
92         }
93
94         /** Override: delete operator */
95         void operator delete(void *p, size_t size) {
96                 ourfree(p);
97         }
98
99         /** Override: new[] operator */
100         void *operator new[](size_t size) {
101                 return ourmalloc(size);
102         }
103
104         /** Override: delete[] operator */
105         void operator delete[](void *p, size_t size) {
106                 ourfree(p);
107         }
108
109         /** @brief Reset the table to its initial state. */
110         void reset() {
111                 memset(table, 0, capacity * sizeof(struct Hashlistnode<_Key, _Val>));
112                 if (zero) {
113                         ourfree(zero);
114                         zero = NULL;
115                 }
116                 size = 0;
117         }
118
119         /** Doesn't work with zero value */
120         _Val getRandomValue() {
121                 while (true) {
122                         unsigned int index = random() & capacitymask;
123                         struct Hashlistnode<_Key, _Val> *bin = &table[index];
124                         if (bin->key != NULL && bin->val != NULL) {
125                                 return bin->val;
126                         }
127                 }
128         }
129
130         void resetAndDeleteKeys() {
131                 for (unsigned int i = 0; i < capacity; i++) {
132                         struct Hashlistnode<_Key, _Val> *bin = &table[i];
133                         if (bin->key != NULL) {
134                                 delete bin->key;
135                                 bin->key = NULL;
136                                 if (bin->val != NULL) {
137                                         bin->val = NULL;
138                                 }
139                         }
140                 }
141                 if (zero) {
142                         ourfree(zero);
143                         zero = NULL;
144                 }
145                 size = 0;
146         }
147
148         void resetAndDeleteVals() {
149                 for (unsigned int i = 0; i < capacity; i++) {
150                         struct Hashlistnode<_Key, _Val> *bin = &table[i];
151                         if (bin->key != NULL) {
152                                 bin->key = NULL;
153                                 if (bin->val != NULL) {
154                                         delete bin->val;
155                                         bin->val = NULL;
156                                 }
157                         }
158                 }
159                 if (zero) {
160                         if (zero->val != NULL)
161                                 delete zero->val;
162                         ourfree(zero);
163                         zero = NULL;
164                 }
165                 size = 0;
166         }
167
168         void resetAndFreeVals() {
169                 for (unsigned int i = 0; i < capacity; i++) {
170                         struct Hashlistnode<_Key, _Val> *bin = &table[i];
171                         if (bin->key != NULL) {
172                                 bin->key = NULL;
173                                 if (bin->val != NULL) {
174                                         ourfree(bin->val);
175                                         bin->val = NULL;
176                                 }
177                         }
178                 }
179                 if (zero) {
180                         if (zero->val != NULL)
181                                 ourfree(zero->val);
182                         ourfree(zero);
183                         zero = NULL;
184                 }
185                 size = 0;
186         }
187
188         /**
189          * @brief Put a key/value pair into the table
190          * @param key The key for the new value; must not be 0 or NULL
191          * @param val The value to store in the table
192          */
193         void put(_Key key, _Val val) {
194                 /* Hashtable cannot handle 0 as a key */
195                 if (!key) {
196                         if (!zero) {
197                                 zero = (struct Hashlistnode<_Key, _Val> *)ourmalloc(sizeof(struct Hashlistnode<_Key, _Val>));
198                                 size++;
199                         }
200                         zero->key = key;
201                         zero->val = val;
202                         return;
203                 }
204
205                 if (size > threshold)
206                         resize(capacity << 1);
207
208                 struct Hashlistnode<_Key, _Val> *search;
209
210                 unsigned int hashcode = hash_function(key);
211                 unsigned int index = hashcode;
212                 do {
213                         index &= capacitymask;
214                         search = &table[index];
215                         if (!search->key) {
216                                 //key is null, probably done
217                                 break;
218                         }
219                         if (search->hashcode == hashcode)
220                                 if (equals(search->key, key)) {
221                                         search->val = val;
222                                         return;
223                                 }
224                         index++;
225                 } while (true);
226
227                 search->key = key;
228                 search->val = val;
229                 search->hashcode = hashcode;
230                 size++;
231         }
232
233         /**
234          * @brief Lookup the corresponding value for the given key
235          * @param key The key for finding the value; must not be 0 or NULL
236          * @return The value in the table, if the key is found; otherwise 0
237          */
238         _Val get(_Key key) const {
239                 struct Hashlistnode<_Key, _Val> *search;
240
241                 /* Hashtable cannot handle 0 as a key */
242                 if (!key) {
243                         if (zero)
244                                 return zero->val;
245                         else
246                                 return (_Val) 0;
247                 }
248
249                 unsigned int hashcode = hash_function(key);
250                 unsigned int oindex = hashcode & capacitymask;
251                 unsigned int index = oindex;
252                 do {
253                         search = &table[index];
254                         if (!search->key) {
255                                 if (!search->val)
256                                         break;
257                         } else
258                         if (hashcode == search->hashcode)
259                                 if (equals(search->key, key))
260                                         return search->val;
261                         index++;
262                         index &= capacitymask;
263                         if (index == oindex)
264                                 break;
265                 } while (true);
266                 return (_Val)0;
267         }
268
269         /**
270          * @brief Remove the given key and return the corresponding value
271          * @param key The key for finding the value; must not be 0 or NULL
272          * @return The value in the table, if the key is found; otherwise 0
273          */
274         _Val remove(_Key key) {
275                 struct Hashlistnode<_Key, _Val> *search;
276
277                 /* Hashtable cannot handle 0 as a key */
278                 if (!key) {
279                         if (!zero) {
280                                 return (_Val)0;
281                         } else {
282                                 _Val v = zero->val;
283                                 ourfree(zero);
284                                 zero = NULL;
285                                 size--;
286                                 return v;
287                         }
288                 }
289
290
291                 unsigned int hashcode = hash_function(key);
292                 unsigned int index = hashcode;
293                 do {
294                         index &= capacitymask;
295                         search = &table[index];
296                         if (!search->key) {
297                                 if (!search->val)
298                                         break;
299                         } else
300                         if (hashcode == search->hashcode)
301                                 if (equals(search->key, key)) {
302                                         _Val v = search->val;
303                                         //empty out this bin
304                                         search->val = (_Val) 1;
305                                         search->key = 0;
306                                         size--;
307                                         return v;
308                                 }
309                         index++;
310                 } while (true);
311                 return (_Val)0;
312         }
313
314         unsigned int getSize() const {
315                 return size;
316         }
317
318
319         /**
320          * @brief Check whether the table contains a value for the given key
321          * @param key The key for finding the value; must not be 0 or NULL
322          * @return True, if the key is found; false otherwise
323          */
324         bool contains(_Key key) const {
325                 struct Hashlistnode<_Key, _Val> *search;
326
327                 /* Hashtable cannot handle 0 as a key */
328                 if (!key) {
329                         return zero != NULL;
330                 }
331
332                 unsigned int index = hash_function(key);
333                 unsigned int hashcode = index;
334                 do {
335                         index &= capacitymask;
336                         search = &table[index];
337                         if (!search->key) {
338                                 if (!search->val)
339                                         break;
340                         } else
341                         if (hashcode == search->hashcode)
342                                 if (equals(search->key, key))
343                                         return true;
344                         index++;
345                 } while (true);
346                 return false;
347         }
348
349         /**
350          * @brief Resize the table
351          * @param newsize The new size of the table
352          */
353         void resize(unsigned int newsize) {
354                 struct Hashlistnode<_Key, _Val> *oldtable = table;
355                 struct Hashlistnode<_Key, _Val> *newtable;
356                 unsigned int oldcapacity = capacity;
357
358                 if ((newtable = (struct Hashlistnode<_Key, _Val> *)ourcalloc(newsize, sizeof(struct Hashlistnode<_Key, _Val>))) == NULL) {
359                         model_print("calloc error %s %d\n", __FILE__, __LINE__);
360                         exit(EXIT_FAILURE);
361                 }
362
363                 table = newtable;                                                                                       // Update the global hashtable upon resize()
364                 capacity = newsize;
365                 capacitymask = newsize - 1;
366
367                 threshold = (unsigned int)(newsize * loadfactor);
368
369                 struct Hashlistnode<_Key, _Val> *bin = &oldtable[0];
370                 struct Hashlistnode<_Key, _Val> *lastbin = &oldtable[oldcapacity];
371                 for (; bin < lastbin; bin++) {
372                         _Key key = bin->key;
373
374                         struct Hashlistnode<_Key, _Val> *search;
375                         if (!key)
376                                 continue;
377
378                         unsigned int hashcode = bin->hashcode;
379                         unsigned int index = hashcode;
380                         do {
381                                 index &= capacitymask;
382                                 search = &table[index];
383                                 index++;
384                         } while (search->key);
385
386                         search->hashcode = hashcode;
387                         search->key = key;
388                         search->val = bin->val;
389                 }
390
391                 ourfree(oldtable);                                                                                              // Free the memory of the old hash table
392         }
393         double getLoadFactor() {return loadfactor;}
394         unsigned int getCapacity() {return capacity;}
395         struct Hashlistnode<_Key, _Val> *table;
396         struct Hashlistnode<_Key, _Val> *zero;
397         unsigned int capacity;
398         unsigned int size;
399 private:
400         unsigned int capacitymask;
401         unsigned int threshold;
402         double loadfactor;
403 };
404
405 #endif/* __HASHTABLE_H__ */