3 void crehash(ctable_t *table) {
4 cResize(table, table->size);
7 ctable_t *cCreate(unsigned int size, float loadfactor) {
12 if((ctable = calloc(1, sizeof(ctable_t))) == NULL) {
13 printf("Calloc error %s %d\n", __FILE__, __LINE__);
17 // Allocate space for the hash table
18 if((nodes = calloc(size, sizeof(cnode_t))) == NULL) {
19 printf("Calloc error %s %d\n", __FILE__, __LINE__);
24 ctable->table = nodes;
26 ctable->mask = (size << 2)-1;
27 ctable->numelements = 0; // Initial number of elements in the hash
28 ctable->loadfactor = loadfactor;
29 ctable->resize=loadfactor*size;
30 ctable->listhead=NULL;
35 //Store objects and their pointers into hash
36 INLINE void cInsert(ctable_t *table, void * key, void *val) {
41 ptr = &table->table[(((unsigned int)key) & table->mask)>>2];
45 ptr->lnext=table->listhead;
50 cnode_t *tmp=malloc(sizeof(cnode_t));
55 tmp->lnext=table->listhead;
59 if(table->numelements > table->resize) {
60 newsize = table->size << 1;
61 cResize(table,newsize);
65 // Search for an address for a given oid
66 INLINE void * cSearch(ctable_t *table, void * key) {
67 //REMOVE HASH FUNCTION CALL TO MAKE SURE IT IS INLINED HERE
68 cnode_t *node = &table->table[(((unsigned int)key) & table->mask)>>2];
71 if(node->key == key) {
79 unsigned int cRemove(ctable_t *table, void * key) {
85 index =(((unsigned int)key) & table->mask)>>2;
88 for (; curr != NULL; curr = curr->next) {
89 if (curr->key == key) { // Find a match in the hash table
90 table->numelements--; // Decrement the number of elements in the global hashtable
91 if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of cnode_t
94 } else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of cnode_t connected
95 curr->key = curr->next->key;
96 curr->val = curr->next->val;
98 curr->next = curr->next->next;
100 } else { // Regular delete from linked listed
101 prev->next = curr->next;
111 unsigned int cResize(ctable_t *table, unsigned int newsize) {
114 int mask=(newsize<<2)-1;
115 int oldsize = table->size;
116 cnode_t *ptr = table->table;
117 cnode_t * ntable=calloc(newsize, sizeof(cnode_t));
119 table->table = ntable;
120 table->size = newsize;
122 table->resize=newsize*table->loadfactor;
124 for(i = 0; i < oldsize; i++) {
126 cnode_t * curr=&ptr[i];
130 cnode_t * next = curr->next;
131 int index =(((unsigned int)curr->key) & mask)>>2;
132 cnode_t * newnode=&ntable[index];
134 if(newnode->key==0) {
135 newnode->key=curr->key;
136 newnode->val=curr->val;
140 cnode_t *tmp=malloc(sizeof(cnode_t));
141 tmp->next=newnode->next;
156 table->listhead=last;
157 free(ptr); //Free the memory of the old hash table
161 //Delete the entire hash table
162 void cDelete(ctable_t *ctable) {
164 cnode_t *ptr, *curr, *next;
167 for(i=0; i<ctable->size; i++) {
170 while(curr != NULL) {