-
Notifications
You must be signed in to change notification settings - Fork 9
/
table.c
88 lines (74 loc) · 1.62 KB
/
table.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
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include "table.h"
#include "utils.h"
typedef struct binder_s *binder_t;
struct binder_s
{
void *key;
void *value;
binder_t prev;
};
struct table_s
{
list_t table[HT_SIZE];
binder_t top;
};
static binder_t binder(void *key, void *value, binder_t prev)
{
binder_t p = checked_malloc(sizeof(*p));
p->key = key;
p->value = value;
p->prev = prev;
return p;
}
table_t tab_empty(void)
{
table_t p = checked_malloc(sizeof(*p));
int i;
p->top = NULL;
for (i = 0; i < HT_SIZE; i++)
p->table[i] = NULL;
return p;
}
void tab_enter(table_t tab, void *key, void *value)
{
int index;
assert(tab && key);
index = ((intptr_t) key) % HT_SIZE;
tab->table[index] = list(binder(key, value, tab->top), tab->table[index]);
tab->top = tab->table[index]->data;
}
void *tab_lookup(table_t tab, void *key)
{
int index;
list_t p;
assert(tab && key);
index = ((intptr_t) key) % HT_SIZE;
for (p = tab->table[index]; p; p = p->next)
if (((binder_t) p->data)->key == key)
return ((binder_t) p->data)->value;
return NULL;
}
void *tab_pop(table_t tab)
{
binder_t bind;
list_t p;
int index;
assert(tab);
bind = tab->top;
assert(bind);
index = ((intptr_t) bind->key) % HT_SIZE;
p = tab->table[index];
assert(p);
tab->table[index] = p->next;
tab->top = bind->prev;
return bind->key;
}
void tab_dump(table_t tab, tab_dump_func_t show)
{
binder_t bind = tab->top;
for (; bind; bind = bind->prev)
show(bind->key, bind->value);
}