#include "hashtable.h" | |
#include <stdlib.h> | |
#include <string.h> | |
#include <stdio.h> | |
void | |
hashtable_error(char* msg) { | |
puts(msg); | |
} | |
hashtable* | |
hashtable_create(unsigned int size) { | |
if (0 == size) { | |
hashtable_error("size must be positive"); | |
return 0; | |
} | |
hashtable* retval = malloc(sizeof(hashtable)); | |
retval->array = calloc(size, sizeof(hashtable_list_item)); | |
retval->size = size; | |
return retval; | |
} | |
unsigned int | |
hash_pow(unsigned int base, unsigned int exponent) { | |
unsigned int i; | |
unsigned int retval = 1; | |
for (i=0; i<exponent; i++) { | |
retval *= base; | |
} | |
return retval; | |
} | |
unsigned int | |
hash(char* s, unsigned int modulus) { | |
unsigned int code = 0; | |
unsigned int i; | |
int len = strlen(s); | |
for(i=0; i<len; i++) { | |
code += s[i] * hash_pow(256, i); | |
} | |
return code % modulus; | |
} | |
void | |
hashtable_insert(hashtable* ht, char* key, char* value) { | |
if (0 == ht) { | |
hashtable_error("first argument is null"); | |
return; | |
} | |
unsigned int slot; | |
slot = hash(key, ht->size); | |
hashtable_list_item* new_item = malloc(sizeof(hashtable_list_item)); | |
new_item->key = key; | |
new_item->value = value; | |
new_item->next = ht->array[slot]; | |
ht->array[slot] = new_item; | |
} | |
char* | |
hashtable_search(hashtable* ht, char* key) { | |
unsigned int slot; | |
slot = hash(key, ht->size); | |
hashtable_list_item* hli; | |
hli = ht->array[slot]; | |
while (0 != hli) { | |
if (0 == strcmp(hli->key, key)) { | |
return hli->value; | |
} | |
hli = hli->next; | |
} | |
return 0; | |
} | |
void | |
hashtable_delete(hashtable* ht, char* key) { | |
unsigned int slot; | |
slot = hash(key, ht->size); | |
hashtable_list_item **hlip; | |
hlip = &(ht->array[slot]); | |
while ( *hlip ) { | |
if (0 == strcmp((*hlip)->key, key)) { | |
(*hlip) = (*hlip)->next; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment