-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtable.c
92 lines (82 loc) · 1.88 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
89
90
91
92
#include <stdio.h>
#include "util.h"
#include "table.h"
#define TABSIZE 127
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wpointer-to-int-cast"
#endif
typedef struct binder_* binder;
struct binder_ {
void *key;
void *value;
binder next;
void* prevtop;
};
struct TAB_table_ {
binder table[TABSIZE];
void *top;
};
static binder Binder(void *key, void *value, binder next, void *prevtop) {
binder b = checked_malloc(sizeof(*b));
b->key = key;
b->value = value;
b->next = next;
b->prevtop = prevtop;
return b;
}
TAB_table TAB_empty(void) {
TAB_table t = checked_malloc(sizeof(*t));
int i;
t->top = NULL;
for(i = 0; i < TABSIZE; i++) {
t->table[i] = NULL;
}
return t;
}
void TAB_enter(TAB_table t, void *key, void* value) {
int index;
assert(t && key);
index = ((unsigned)key) % TABSIZE;
t->table[index] = Binder(key, value, t->table[index], t->top);
t->top = key;
}
void* TAB_look(TAB_table t, void* key) {
int index;
binder b;
assert(t);
assert(key);
index = ((unsigned) key) % TABSIZE;
for(b = t->table[index]; b; b=b->next) {
if (b->key == key) {
return b->value;
}
}
return NULL;
}
void *TAB_pop(TAB_table t) {
void *k;
binder b;
int index;
assert(t);
k = t->top;
assert(k);
index = ((unsigned)k) % TABSIZE;
b = t->table[index];
assert(b);
t->table[index] = b->next;
t->top = b->prevtop;
return b->key;
}
void TAB_dump(TAB_table t, void (*show)(void* key, void* value)) {
void* k = t->top;
int index = ((unsigned)k) % TABSIZE;
binder b = t->table[index];
if(b == NULL) return;
t->table[index] = b->next;
t->top = b->prevtop;
show(b->key, b->value);
TAB_dump(t, show);
assert(t->top == b->prevtop && t->table[index] == b->next);\
t->top = k;
t->table[index] = b;
}