From 3efd96ff79f4f5669c3422a1f592f09176c77121 Mon Sep 17 00:00:00 2001 From: Jon Bergli Heier Date: Sat, 15 Aug 2009 18:07:02 +0200 Subject: Added a hash table to keep track of words. Moved the sdbm hash function into sdbm.c. Init and free users and words inside the channel loop. Increased the size of the user hash table to 1000. --- word.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 word.c (limited to 'word.c') diff --git a/word.c b/word.c new file mode 100644 index 0000000..bf1fada --- /dev/null +++ b/word.c @@ -0,0 +1,49 @@ +#include +#include + +#include "word.h" +#include "sdbm.h" + +struct word_t *words; + +void word_init() { + words = malloc(sizeof(struct word_t) * WORDS_MAX); + memset(words, 0, sizeof(struct word_t) * WORDS_MAX); +} + +struct word_t *word_get(char *name) { + unsigned long hash = sdbm(name); + int index = hash % WORDS_MAX; + + struct word_t *word = &words[index]; + /* Fetch next word if hash doesn't match or the word differ (hash matching first). */ + while((word->hash != hash || (word->name && strcmp(name, word->name) != 0)) && word->next) word = word->next; + /* Add new word if the word exists, but both hash and name doesn't match. */ + if(word->name && (word->hash != hash || strcmp(name, word->name) != 0)) { + struct word_t *temp_word = malloc(sizeof(struct word_t)); + word->next = temp_word; + word = temp_word; + word->name = NULL; + } + if(!word->name) { + word->hash = hash; + word->name = strdup(name); + word->count = 0; + word->next = NULL; + } + return word; +} + +void word_free() { + struct word_t *word; + for(int i = 0; i < WORDS_MAX; i++) { + word = words[i].next; + while(word) { + struct word_t *temp = word->next; + free(word->name); + free(word); + word = temp; + } + } + free(words); +} -- cgit v1.2.3