├── hash_table.c └── hash_table.h /hash_table.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "hash_table.h" 5 | 6 | hash_table* create_htab() 7 | { 8 | hash_table* htab; 9 | 10 | htab = (hash_table*)malloc(sizeof(hash_table)); 11 | int i; for(i = 0; i < HTAB_SIZE; i++) htab->nodes[i] = NULL; 12 | 13 | return htab; 14 | } 15 | 16 | void destroy_htab(hash_table* htab) 17 | { 18 | int i; for(i = 0; i < HTAB_SIZE; i++) 19 | { 20 | if(htab->nodes[i]) 21 | { 22 | free(htab->nodes[i]->key); 23 | free(htab->nodes[i]); 24 | } 25 | } 26 | 27 | free(htab); 28 | 29 | htab = NULL; 30 | } 31 | 32 | int htab_add(hash_table* htab, char* k, int v) 33 | { 34 | int hash = htab_hash(k); 35 | 36 | // If the node is not already occupied, allocate space, and copy the key/value pair. 37 | if(htab->nodes[hash] == NULL) htab->nodes[hash] = malloc(sizeof(htable_node)); 38 | else return 1; 39 | 40 | htab->nodes[hash]->key = (char*)malloc(sizeof(char) * (strlen(k) + 1)); 41 | 42 | strcpy(htab->nodes[hash]->key, k); 43 | htab->nodes[hash]->value = v; 44 | 45 | return 0; 46 | } 47 | 48 | int htab_find(hash_table* htab, char* key) 49 | { 50 | int hash = htab_hash(key); 51 | 52 | if(htab->nodes[hash] != NULL) return htab->nodes[hash]->value; 53 | else return -1; 54 | } 55 | 56 | unsigned int htab_hash(char* k) 57 | { 58 | unsigned int hash = 1; 59 | 60 | char* c; for(c = k; *c; c++) 61 | hash += (hash << *c) - *c; 62 | 63 | return hash % HTAB_SIZE; 64 | } 65 | -------------------------------------------------------------------------------- /hash_table.h: -------------------------------------------------------------------------------- 1 | #ifndef HASH_TABLE_H_ 2 | #define HASH_TABLE_H_ 3 | 4 | #define KEY_LENGTH 64 5 | #define HTAB_SIZE 4096 6 | 7 | typedef struct 8 | { 9 | char* key; 10 | int value; 11 | } htable_node; 12 | 13 | typedef struct 14 | { 15 | int num_nodes; 16 | htable_node* nodes[HTAB_SIZE]; 17 | } hash_table; 18 | 19 | hash_table* create_htab(); 20 | void destroy_htab(hash_table* htab); 21 | 22 | inline int htab_add(hash_table* htab, char* key, int value); 23 | inline int htab_find(hash_table* htab, char* key); 24 | 25 | inline unsigned int htab_hash(char* key); 26 | 27 | #endif 28 | --------------------------------------------------------------------------------