|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <string.h> |
| 4 | + |
| 5 | +#include "nlist.h" |
| 6 | +#include "io.h" |
| 7 | + |
| 8 | +#define HASHSIZE 101 |
| 9 | + |
| 10 | +static struct nlist *hashtab[HASHSIZE]; /* pointer table */ |
| 11 | + |
| 12 | +/* hash: form hash value for string s */ |
| 13 | +unsigned hash(char *s) { |
| 14 | + unsigned hashval; |
| 15 | + |
| 16 | + for (hashval = 0; *s != '\0' ; s++) |
| 17 | + hashval = *s + 31 * hashval; |
| 18 | + |
| 19 | + return hashval % HASHSIZE; |
| 20 | +} |
| 21 | + |
| 22 | +/* lookup: look for s in hashtab */ |
| 23 | +struct nlist *lookup(char *s) { |
| 24 | + struct nlist *np; |
| 25 | + |
| 26 | + for (np = hashtab[hash(s)] ; np != NULL ; np = np -> next) |
| 27 | + if (strcmp(s, np -> name) == 0) |
| 28 | + return np; /* found */ |
| 29 | + return NULL; /* not found */ |
| 30 | +} |
| 31 | + |
| 32 | +/* install: put(name, defn) in hashtab */ |
| 33 | +struct nlist *install(char* name, char* defn) { |
| 34 | + struct nlist *np; |
| 35 | + unsigned hashval; |
| 36 | + |
| 37 | + if ((np = lookup(name)) == NULL) { /* not found */ |
| 38 | + np = (struct nlist *) malloc(sizeof(*np)); |
| 39 | + if (np == NULL || (np -> name = _strdup(name)) == NULL) |
| 40 | + return NULL; |
| 41 | + hashval = hash(name); |
| 42 | + np -> next = hashtab[hashval]; |
| 43 | + hashtab[hashval] = np; |
| 44 | + } else /* that means its already there */ |
| 45 | + free((void*) np -> defn); /* free previous defn */ |
| 46 | + if ((np -> defn = _strdup(defn)) == NULL) |
| 47 | + return NULL; |
| 48 | + return np; |
| 49 | +} |
| 50 | + |
| 51 | +/* undef: removes a name from the hashtab */ |
| 52 | +int undef(char* name) { |
| 53 | + struct nlist *np; |
| 54 | + |
| 55 | + if ((np = lookup(name)) == NULL) |
| 56 | + return 1; /* the name was not found */ |
| 57 | + |
| 58 | + struct nlist *prev_np = NULL; |
| 59 | + unsigned hashval = hash(name); |
| 60 | + for (np = hashtab[hashval] ; np != NULL; prev_np = np, np = np -> next) { |
| 61 | + if (strcmp(np -> name, name) == 0) { /* found the node with that name */ |
| 62 | + if (prev_np == NULL) /* at the beginning ? */ |
| 63 | + hashtab[hashval] = np -> next; |
| 64 | + else /* somewhere in the middle */ |
| 65 | + prev_np -> next = np -> next; |
| 66 | + /* free the memory */ |
| 67 | + free(np -> name); |
| 68 | + free(np -> defn); |
| 69 | + free(np); |
| 70 | + |
| 71 | + return 0; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return 1; /* name not found */ |
| 76 | +} |
| 77 | + |
0 commit comments