summaryrefslogtreecommitdiff
path: root/word.c
diff options
context:
space:
mode:
Diffstat (limited to 'word.c')
-rw-r--r--word.c49
1 files changed, 49 insertions, 0 deletions
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 <stdlib.h>
+#include <string.h>
+
+#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);
+}