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 #define hash_func(h, key) (key >= 0 ? (key % h->size) : (-key % h->size))
17 /* Create a hash table. The size is just a hint, not a maximum. */
19 struct hash *create_hash(size)
24 h = (struct hash *) malloc(sizeof(struct hash));
25 if (h == (struct hash *) NULL)
26 return((struct hash *) NULL);
28 h->data = (struct bucket **) malloc(size * sizeof(char *));
29 if (h->data == (struct bucket **) NULL) {
31 return((struct hash *) NULL);
33 bzero(h->data, size * sizeof(char *));
37 /* Lookup an object in the hash table. Returns the value associated with
38 * the key, or NULL (thus NULL is not a very good value to store...)
41 char *hash_lookup(h, key)
45 register struct bucket *b;
47 b = h->data[hash_func(h, key)];
48 while (b && b->key != key)
50 if (b && b->key == key)
57 /* Update an existing object in the hash table. Returns 1 if the object
58 * existed, or 0 if not.
61 int hash_update(h, key, value)
66 register struct bucket *b;
68 b = h->data[hash_func(h, key)];
69 while (b && b->key != key)
71 if (b && b->key == key) {
79 /* Store an item in the hash table. Returns 0 if the key was not previously
80 * there, 1 if it was, or -1 if we ran out of memory.
83 int hash_store(h, key, value)
88 register struct bucket *b, **p;
90 p = &(h->data[hash_func(h, key)]);
92 b = *p = (struct bucket *) malloc(sizeof(struct bucket));
93 if (b == (struct bucket *) NULL)
101 for (b = *p; b && b->key != key; b = *p)
102 p = (struct bucket **) *p;
103 if (b && b->key == key) {
107 b = *p = (struct bucket *) malloc(sizeof(struct bucket));
108 if (b == (struct bucket *) NULL)
117 /* Search through the hash table for a given value. For each piece of
118 * data with that value, call the callback proc with the corresponding key.
121 hash_search(h, value, callback)
123 register char *value;
126 register struct bucket *b, **p;
128 for (p = &(h->data[h->size - 1]); p >= h->data; p--) {
129 for (b = *p; b; b = b->next) {
130 if (b->data == value)
137 /* Step through the hash table, calling the callback proc with each key.
140 hash_step(h, callback, hint)
145 register struct bucket *b, **p;
147 for (p = &(h->data[h->size - 1]); p >= h->data; p--) {
148 for (b = *p; b; b = b->next) {
149 (*callback)(b->key, b->data, hint);
155 /* Deallocate all of the memory associated with a table */
160 register struct bucket *b, **p, *b1;
162 for (p = &(h->data[h->size - 1]); p >= h->data; p--) {
163 for (b = *p; b; b = b1) {