|
| 1 | +#include "dict.h" |
| 2 | +#include <stdio.h> |
| 3 | +#include <stdlib.h> |
| 4 | + |
| 5 | +/* simple constructor */ |
| 6 | +Dictionary *create_dict(void) |
| 7 | +{ |
| 8 | + Dictionary *p_dic = malloc(sizeof(Dictionary)); |
| 9 | + if (p_dic) |
| 10 | + { |
| 11 | + p_dic->number_of_elements = 0; |
| 12 | + |
| 13 | + /* initializes the elemens of the array with NULL-pointer */ |
| 14 | + for (int i = 0; i < MAXELEMENTS; i++) |
| 15 | + { |
| 16 | + p_dic->elements[i] = NULL; |
| 17 | + } |
| 18 | + |
| 19 | + return p_dic; |
| 20 | + } |
| 21 | + else |
| 22 | + { |
| 23 | + printf("unable to create a dictionary\n"); |
| 24 | + return NULL; |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +/* |
| 29 | + utility function |
| 30 | + sdbm hash algorithm |
| 31 | + returns a hashcode for the given string 's' |
| 32 | +*/ |
| 33 | +int get_hash(char s[]) |
| 34 | +{ |
| 35 | + unsigned int hash_code = 0; |
| 36 | + |
| 37 | + /* iterates over string at each character */ |
| 38 | + for (int counter = 0; s[counter] != '\0'; counter++) |
| 39 | + { |
| 40 | + /* actual computing of the hash code */ |
| 41 | + hash_code = |
| 42 | + s[counter] + (hash_code << 6) + (hash_code << 16) - hash_code; |
| 43 | + } |
| 44 | + |
| 45 | + /* % modulo is for fitting the index in array. */ |
| 46 | + return hash_code % MAXELEMENTS; |
| 47 | +} |
| 48 | + |
| 49 | +int add_item_label(Dictionary *dic, char label[], void *item) |
| 50 | +{ |
| 51 | + unsigned int index = get_hash(label); |
| 52 | + |
| 53 | + /* make sure index is fitting */ |
| 54 | + if (index < MAXELEMENTS) |
| 55 | + { |
| 56 | + dic->elements[index] = item; |
| 57 | + return 0; |
| 58 | + } |
| 59 | + |
| 60 | + /* error case */ |
| 61 | + return -1; |
| 62 | +} |
| 63 | + |
| 64 | +int add_item_index(Dictionary *dic, int index, void *item) |
| 65 | +{ |
| 66 | + /* make sure whether this place is already given */ |
| 67 | + if (!dic->elements[index]) |
| 68 | + { |
| 69 | + dic->elements[index] = item; |
| 70 | + return 0; |
| 71 | + } |
| 72 | + |
| 73 | + /* error case */ |
| 74 | + return -1; |
| 75 | +} |
| 76 | + |
| 77 | +void *get_element_label(Dictionary *dict, char s[]) |
| 78 | +{ |
| 79 | + int index = get_hash(s); |
| 80 | + if (dict->elements[index]) |
| 81 | + { |
| 82 | + return dict->elements[index]; |
| 83 | + } |
| 84 | + |
| 85 | + printf("None entry at given label\n"); |
| 86 | + return NULL; |
| 87 | +} |
| 88 | + |
| 89 | +void *get_element_index(Dictionary *dict, int index) |
| 90 | +{ |
| 91 | + if (index >= 0 && index < MAXELEMENTS) |
| 92 | + { |
| 93 | + return dict->elements[index]; |
| 94 | + } |
| 95 | + |
| 96 | + printf("index out of bounds!\n"); |
| 97 | + return NULL; |
| 98 | +} |
| 99 | + |
| 100 | +void destroy(Dictionary *dict) { free(dict); } |
0 commit comments