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>
15 extern char *malloc();
18 #define hash_func(h, key) (key >= 0 ? (key % h->size) : (-key % h->size))
20 /* Create a hash table. The size is just a hint, not a maximum. */
22 struct hash *create_hash(size)
27 h = (struct hash *) malloc(sizeof(struct hash));
28 if (h == (struct hash *) NULL)
29 return((struct hash *) NULL);
31 h->data = (struct bucket **) malloc(size * sizeof(char *));
32 if (h->data == (struct bucket **) NULL) {
34 return((struct hash *) NULL);
36 memset(h->data, 0, size * sizeof(char *));
40 /* Lookup an object in the hash table. Returns the value associated with
41 * the key, or NULL (thus NULL is not a very good value to store...)
44 char *hash_lookup(h, key)
48 register struct bucket *b;
50 b = h->data[hash_func(h, key)];
51 while (b && b->key != key)
53 if (b && b->key == key)
60 /* Update an existing object in the hash table. Returns 1 if the object
61 * existed, or 0 if not.
64 int hash_update(h, key, value)
69 register struct bucket *b;
71 b = h->data[hash_func(h, key)];
72 while (b && b->key != key)
74 if (b && b->key == key) {
82 /* Store an item in the hash table. Returns 0 if the key was not previously
83 * there, 1 if it was, or -1 if we ran out of memory.
86 int hash_store(h, key, value)
91 register struct bucket *b, **p;
93 p = &(h->data[hash_func(h, key)]);
95 b = *p = (struct bucket *) malloc(sizeof(struct bucket));
96 if (b == (struct bucket *) NULL)
104 for (b = *p; b && b->key != key; b = *p)
105 p = (struct bucket **) *p;
106 if (b && b->key == key) {
110 b = *p = (struct bucket *) malloc(sizeof(struct bucket));
111 if (b == (struct bucket *) NULL)
120 /* Search through the hash table for a given value. For each piece of
121 * data with that value, call the callback proc with the corresponding key.
124 hash_search(h, value, callback)
126 register char *value;
129 register struct bucket *b, **p;
131 for (p = &(h->data[h->size - 1]); p >= h->data; p--) {
132 for (b = *p; b; b = b->next) {
133 if (b->data == value)
140 /* Step through the hash table, calling the callback proc with each key.
143 hash_step(h, callback, hint)
148 register struct bucket *b, **p;
150 for (p = &(h->data[h->size - 1]); p >= h->data; p--) {
151 for (b = *p; b; b = b->next) {
152 (*callback)(b->key, b->data, hint);
158 /* Deallocate all of the memory associated with a table */
163 register struct bucket *b, **p, *b1;
165 for (p = &(h->data[h->size - 1]); p >= h->data; p--) {
166 for (b = *p; b; b = b1) {