3 * Generic hash table routines. Uses integer keys to store integer values.
5 * (c) Copyright 1996 by the Massachusetts Institute of Technology.
6 * For copying and distribution information, please see the file
10 #include <mit-copyright.h>
13 /* #include <moira.h> */
16 struct int_bucket *next;
22 struct int_bucket **data;
25 #define int_hash_func(h, key) (key >= 0 ? (key % h->size) : (-key % h->size))
27 /* Create an int_hash table. The size is just a hint, not a maximum. */
29 struct int_hash *create_int_hash(int size)
33 h = malloc(sizeof(struct int_hash));
37 h->data = malloc(size * sizeof(struct int_bucket *));
43 memset(h->data, 0, size * sizeof(char *));
47 /* Look up an object in the int_hash table. Returns the value associated with
48 * the key, or NULL (thus NULL is not a very good value to store...)
51 int int_hash_lookup(struct int_hash *h, int key)
55 b = h->data[int_hash_func(h, key)];
56 while (b && b->key != key)
58 if (b && b->key == key)
65 /* Update an existing object in the int_hash table. Returns 1 if the object
66 * existed, or 0 if not.
69 int int_hash_update(struct int_hash *h, int key, int value)
73 b = h->data[int_hash_func(h, key)];
74 while (b && b->key != key)
76 if (b && b->key == key)
86 /* Store an item in the int_hash table. Returns 0 if the key was not
87 * previously there, 1 if it was, or -1 if we ran out of memory.
90 int int_hash_store(struct int_hash *h, int key, int value)
92 struct int_bucket *b, **p;
94 p = &(h->data[int_hash_func(h, key)]);
97 b = *p = malloc(sizeof(struct int_bucket));
106 for (b = *p; b && b->key != key; b = *p)
107 p = (struct int_bucket **) *p;
108 if (b && b->key == key)
113 b = *p = malloc(sizeof(struct int_bucket));
123 /* Search through the int_hash table for a given value. For each piece of
124 * data with that value, call the callback proc with the corresponding key.
127 int int_hash_search(struct int_hash *h, int value, void (*callback)())
129 struct int_bucket *b, **p;
131 for (p = &(h->data[h->size - 1]); p >= h->data; p--)
133 for (b = *p; b; b = b->next)
135 if (b->data == value)
142 /* Step through the int_hash table, calling the callback proc with each key.
145 int int_hash_step(struct int_hash *h, void (*callback)(), char *hint)
147 struct int_bucket *b, **p;
149 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);
157 /* Deallocate all of the memory associated with a table */
159 int int_hash_destroy(struct int_hash *h)
161 struct int_bucket *b, **p, *b1;
163 for (p = &(h->data[h->size - 1]); p >= h->data; p--)
165 for (b = *p; b; b = b1)