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>
19 #define hash_func(h, key) (key >= 0 ? (key % h->size) : (-key % h->size))
21 /* Create a hash table. The size is just a hint, not a maximum. */
23 struct hash *create_hash(int size)
27 h = malloc(sizeof(struct hash));
31 h->data = malloc(size * sizeof(char *));
37 memset(h->data, 0, size * sizeof(char *));
41 /* Lookup an object in the hash table. Returns the value associated with
42 * the key, or NULL (thus NULL is not a very good value to store...)
45 char *hash_lookup(struct hash *h, int key)
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(struct hash *h, int key, char *value)
67 b = h->data[hash_func(h, key)];
68 while (b && b->key != key)
70 if (b && b->key == key)
80 /* Store an item in the hash table. Returns 0 if the key was not previously
81 * there, 1 if it was, or -1 if we ran out of memory.
84 int hash_store(struct hash *h, int key, char *value)
86 struct bucket *b, **p;
88 p = &(h->data[hash_func(h, key)]);
91 b = *p = malloc(sizeof(struct bucket));
100 for (b = *p; b && b->key != key; b = *p)
101 p = (struct bucket **) *p;
102 if (b && b->key == key)
107 b = *p = malloc(sizeof(struct bucket));
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(struct hash *h, char *value, void (*callback)())
123 struct bucket *b, **p;
125 for (p = &(h->data[h->size - 1]); p >= h->data; p--)
127 for (b = *p; b; b = b->next)
129 if (b->data == value)
136 /* Step through the hash table, calling the callback proc with each key.
139 hash_step(struct hash *h, void (*callback)(), char *hint)
141 struct bucket *b, **p;
143 for (p = &(h->data[h->size - 1]); p >= h->data; p--)
145 for (b = *p; b; b = b->next)
146 (*callback)(b->key, b->data, hint);
151 /* Deallocate all of the memory associated with a table */
153 hash_destroy(struct hash *h)
155 struct bucket *b, **p, *b1;
157 for (p = &(h->data[h->size - 1]); p >= h->data; p--)
159 for (b = *p; b; b = b1)