-
Notifications
You must be signed in to change notification settings - Fork 5
/
tab.c
53 lines (48 loc) · 1014 Bytes
/
tab.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
/* A Dictionary */
#include <stdlib.h>
#include <string.h>
#include "mkfn.h"
struct tab {
char **keys;
void **vals;
int n;
int *next;
int head[256];
};
struct tab *tab_alloc(int sz)
{
struct tab *tab = malloc(sizeof(*tab));
int i;
memset(tab, 0, sizeof(*tab));
tab->keys = malloc(sz * sizeof(tab->keys[0]));
tab->vals = malloc(sz * sizeof(tab->vals[0]));
tab->next = malloc(sz * sizeof(tab->next[0]));
for (i = 0; i < 256; i++)
tab->head[i] = -1;
return tab;
}
void tab_free(struct tab *tab)
{
free(tab->keys);
free(tab->vals);
free(tab->next);
free(tab);
}
void tab_put(struct tab *tab, char *k, void *v)
{
tab->keys[tab->n] = k;
tab->vals[tab->n] = v;
tab->next[tab->n] = tab->head[(unsigned char) k[0]];
tab->head[(unsigned char) k[0]] = tab->n;
tab->n++;
}
void *tab_get(struct tab *tab, char *k)
{
int i = tab->head[(unsigned char) k[0]];
while (i >= 0) {
if (k[1] == tab->keys[i][1] && !strcmp(k, tab->keys[i]))
return tab->vals[i];
i = tab->next[i];
}
return NULL;
}