-
Notifications
You must be signed in to change notification settings - Fork 0
/
word.c
111 lines (93 loc) · 2.21 KB
/
word.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "word.h"
#include "code.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
/*
Creates a word by:
- Allocating memory for word
- Allocating memory for symbols (with length len)
- Copying syms array into word->syms
- Setting length
*/
Word *word_create(uint8_t *syms, uint32_t len) {
Word *word = (Word *) calloc(1, sizeof(Word));
if (word == NULL) {
return NULL;
}
word->syms = (uint8_t *) calloc(len, sizeof(uint8_t));
if (word->syms == NULL) {
free(word);
return NULL;
}
memcpy(word->syms, syms, len);
word->len = len;
return word;
}
/*
Creates a new word that appends the symbol given by using word_create and setting the last character to the new symbol->
*/
Word *word_append_sym(Word *w, uint8_t sym) {
if (w == NULL) {
return NULL;
}
Word *word = (Word *) calloc(1, sizeof(Word));
if (word == NULL) {
return NULL;
}
word->syms = (uint8_t *) calloc(w->len + 1, sizeof(uint8_t));
if (word->syms == NULL) {
free(word);
return NULL;
}
memcpy(word->syms, w->syms, w->len);
word->syms[w->len] = sym;
word->len = w->len + 1;
return word;
}
/*
Frees and NULLs w
*/
void word_delete(Word *w) {
if (w == NULL) {
return;
}
if (w->syms != NULL) {
free(w->syms);
}
free(w);
}
/*
Creates new WordTable with size MAX_CODE
*/
WordTable *wt_create(void) {
WordTable *wt = (WordTable *) calloc(MAX_CODE, sizeof(Word *));
uint8_t *syms = (uint8_t *) calloc(1, sizeof(uint8_t));
Word *word = word_create(syms, 0);
wt[EMPTY_CODE] = word;
free(syms);
return wt;
}
/*
Resets wordtable by iteratively traversing word list and deleting all words in table (until null word)
*/
void wt_reset(WordTable *wt) {
for (int i = 1; i < MAX_CODE; i++) {
if (i == EMPTY_CODE || wt[i] == NULL) {
continue;
}
word_delete(wt[i]);
wt[i] = NULL;
}
return;
}
/*
Frees all words in WordTable, then frees wordtable->
*/
void wt_delete(WordTable *wt) {
wt_reset(wt);
word_delete(wt[EMPTY_CODE]);
free(wt);
return;
}