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