-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6-5.c
More file actions
134 lines (113 loc) · 2 KB
/
6-5.c
File metadata and controls
134 lines (113 loc) · 2 KB
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <stdio.h>
#include <stdlib.h>
#define HASHSIZE 101
typedef struct nlist Nlist;
struct nlist {
Nlist *next;
char *name;
char *defn;
};
unsigned hash(char *);
Nlist *lalloc();
Nlist *lookup(char *);
Nlist *install(char *, char *);
void undef(char *);
char *sdup(char *);
int scmp(char *, char *);
void scpy(char *, char *);
int slen(char *);
static Nlist *hashtab[HASHSIZE];
void main()
{
Nlist *l;
l = install("IN", "1");
l = install("IN", "0");
l = lookup("IN");
if (l)
printf("result: %s\tval: %s\n", l->name, l->defn);
undef("TEST");
undef("IN");
undef("IN");
l = lookup("IN");
if (l)
printf("result: %s\tval: %s\n", l->name, l->defn);
}
void undef(char *def)
{
Nlist *np;
if (!(np = lookup(def))) {
printf("undef: %s not defined\n", def);
return;
}
free(np->next);
free(np->name);
free(np->defn);
free(np);
hashtab[hash(def)] = 0;
}
unsigned hash(char *s)
{
unsigned hashval;
for (hashval = 0; *s != 0; s++)
hashval = *s + 31 * hashval;
return hashval % HASHSIZE;
}
Nlist *install(char *name, char *defn)
{
Nlist *np;
unsigned hashval;
if ((np = lookup(name)) == 0) {
np = lalloc();
if (np == 0 || (np->name = sdup(name)) == 0)
return 0;
hashval = hash(name);
np->next = hashtab[hashval];
hashtab[hashval] = np;
} else
free((void *) np->defn);
if ((np->defn = sdup(defn)) == 0)
return 0;
return np;
}
Nlist *lookup(char *s)
{
Nlist *np;
for (np = hashtab[hash(s)]; np != 0; np = np->next)
if (scmp(s, np->name) == 0)
return np;
return 0;
}
int scmp(char *s1, char *s2)
{
int c;
for (c = 0; s1[c] == s2[c]; c++) {
if (s1[c] == 0)
return 0;
}
return s1[c] - s2[c];
}
Nlist *lalloc()
{
return (Nlist *) malloc(sizeof(Nlist));
}
/* does not protect from overflow: user beware */
void scpy(char *s1, char *s2)
{
int c;
for (c = 0; s1[c]; c++)
s2[c] = s1[c];
}
int slen(char *s)
{
int c;
for (c = 0; s[c]; c++)
;
return c;
}
char *sdup(char *s)
{
char *str;
str = malloc(slen(s) + 1);
scpy(s, str);
return str;
}