2 * @brief Hashtable. Standard chained bucket variety.
11 template<typename _Key, typename _Val>
15 struct hashlistnode<_Key,_Val> *next;
18 template<typename _Key, typename _Val, typename _KeyInt, int _Shift>
21 HashTable(unsigned int initialcapacity=1024, double factor=0.5) {
22 // Allocate space for the hash table
23 table = (struct hashlistnode<_Key,_Val> **) calloc(initialcapacity, sizeof(struct hashlistnode<_Key,_Val> *));
25 capacity = initialcapacity;
26 threshold = (unsigned int) (initialcapacity*loadfactor);
27 mask = (capacity << _Shift)-1;
28 size = 0; // Initial number of elements in the hash
32 for(unsigned int i=0;i<capacity;i++) {
33 struct hashlistnode<_Key,_Val> * bin = table[i];
35 struct hashlistnode<_Key,_Val> * next=bin->next;
43 /** Reset the table to its initial state. */
45 for(int i=0;i<capacity;i++) {
46 struct hashlistnode<_Key,_Val> * bin = table[i];
48 struct hashlistnode<_Key,_Val> * next=bin->next;
53 memset(table, 0, capacity*sizeof(struct hashlistnode<_Key, _Val> *));
57 /** Put a key value pair into the table. */
58 void put(_Key key, _Val val) {
59 if(size > threshold) {
61 unsigned int newsize = capacity << 1;
65 struct hashlistnode<_Key,_Val> *ptr = table[(((_KeyInt)key) & mask)>>_Shift];
67 struct hashlistnode<_Key,_Val> *search = ptr;
70 if (search->key==key) {
77 struct hashlistnode<_Key,_Val> *newptr=(struct hashlistnode<_Key,_Val> *)malloc(sizeof(struct hashlistnode<_Key,_Val>));
81 table[(((_KeyInt)key)&mask)>>_Shift]=newptr;
84 /** Lookup the corresponding value for the given key. */
86 struct hashlistnode<_Key,_Val> *search = table[(((_KeyInt)key) & mask)>>_Shift];
89 if (search->key==key) {
97 /** Check whether the table contains a value for the given key. */
98 bool contains(_Key key) {
99 struct hashlistnode<_Key,_Val> *search = table[(((_KeyInt)key) & mask)>>_Shift];
101 while(search!=NULL) {
102 if (search->key==key) {
110 /** Resize the table. */
111 void resize(unsigned int newsize) {
112 struct hashlistnode<_Key,_Val> ** oldtable = table;
113 struct hashlistnode<_Key,_Val> ** newtable;
114 unsigned int oldcapacity = capacity;
116 if((newtable = (struct hashlistnode<_Key,_Val> **) calloc(newsize, sizeof(struct hashlistnode<_Key,_Val> *))) == NULL) {
117 printf("Calloc error %s %d\n", __FILE__, __LINE__);
121 table = newtable; //Update the global hashtable upon resize()
123 threshold = (unsigned int) (newsize * loadfactor);
124 mask = (newsize << _Shift)-1;
126 for(unsigned int i = 0; i < oldcapacity; i++) {
127 struct hashlistnode<_Key, _Val> * bin = oldtable[i];
131 struct hashlistnode<_Key, _Val> * next=bin->next;
133 unsigned int index = (((_KeyInt)key) & mask) >>_Shift;
134 struct hashlistnode<_Key, _Val> * tmp=newtable[index];
141 free(oldtable); //Free the memory of the old hash table
145 struct hashlistnode<_Key,_Val> **table;
146 unsigned int capacity;
149 unsigned int threshold;