3 * Generic hash table routines. Uses integer keys to store char * values.
5 * (c) Copyright 1988 by the Massachusetts Institute of Technology.
6 * For copying and distribution information, please see the file
10 #include <mit-copyright.h>
14 extern char *malloc();
17 #define hash_func(h, key) (key >= 0 ? (key % h->size) : (-key % h->size))
19 /* Create a hash table. The size is just a hint, not a maximum. */
21 struct hash *create_hash(size)
26 h = (struct hash *) malloc(sizeof(struct hash));
27 if (h == (struct hash *) NULL)
28 return((struct hash *) NULL);
30 h->data = (struct bucket **) malloc(size * sizeof(char *));
31 if (h->data == (struct bucket **) NULL) {
33 return((struct hash *) NULL);
35 bzero(h->data, size * sizeof(char *));
39 /* Lookup an object in the hash table. Returns the value associated with
40 * the key, or NULL (thus NULL is not a very good value to store...)
43 char *hash_lookup(h, key)
47 register struct bucket *b;
49 b = h->data[hash_func(h, key)];
50 while (b && b->key != key)
52 if (b && b->key == key)
59 /* Update an existing object in the hash table. Returns 1 if the object
60 * existed, or 0 if not.
63 int hash_update(h, key, value)
68 register struct bucket *b;
70 b = h->data[hash_func(h, key)];
71 while (b && b->key != key)
73 if (b && b->key == key) {
81 /* Store an item in the hash table. Returns 0 if the key was not previously
82 * there, 1 if it was, or -1 if we ran out of memory.
85 int hash_store(h, key, value)
90 register struct bucket *b, **p;
92 p = &(h->data[hash_func(h, key)]);
94 b = *p = (struct bucket *) malloc(sizeof(struct bucket));
95 if (b == (struct bucket *) NULL)
103 for (b = *p; b && b->key != key; b = *p)
104 p = (struct bucket **) *p;
105 if (b && b->key == key) {
109 b = *p = (struct bucket *) malloc(sizeof(struct bucket));
110 if (b == (struct bucket *) NULL)
119 /* Search through the hash table for a given value. For each piece of
120 * data with that value, call the callback proc with the corresponding key.
123 hash_search(h, value, callback)
125 register char *value;
128 register struct bucket *b, **p;
130 for (p = &(h->data[h->size - 1]); p >= h->data; p--) {
131 for (b = *p; b; b = b->next) {
132 if (b->data == value)
139 /* Step through the hash table, calling the callback proc with each key.
142 hash_step(h, callback, hint)
147 register struct bucket *b, **p;
149 for (p = &(h->data[h->size - 1]); p >= h->data; p--) {
150 for (b = *p; b; b = b->next) {
151 (*callback)(b->key, b->data, hint);
157 /* Deallocate all of the memory associated with a table */
162 register struct bucket *b, **p, *b1;
164 for (p = &(h->data[h->size - 1]); p >= h->data; p--) {
165 for (b = *p; b; b = b1) {