3 * Hash table implemenation
9 #define Bucket JOIN(HASHTYPE,Buket)
10 #define Bucket_s JOIN(HASHTYPE,Buket_s)
12 typedef struct Bucket_s * Bucket;
17 HTKEYTYPE key; /*!< hash key */
19 HTDATATYPE * data; /*!< pointer to hashed data */
20 int dataCount; /*!< length of data (0 if unknown) */
22 Bucket next; /*!< pointer to next item in bucket */
28 int numBuckets; /*!< number of hash buckets */
29 Bucket * buckets; /*!< hash bucket array */
30 hashFunctionType fn; /*!< generate hash value for key */
31 hashEqualityType eq; /*!< compare hash keys for equality */
34 hashFreeData freeData;
39 * Find entry in hash table.
40 * @param ht pointer to hash table
41 * @param key pointer to key value
42 * @return pointer to hash bucket of key (or NULL)
45 Bucket HASHPREFIX(findEntry)(HASHTYPE ht, HTKEYTYPE key)
50 hash = ht->fn(key) % ht->numBuckets;
51 b = ht->buckets[hash];
53 while (b && b->key && ht->eq(b->key, key))
59 HASHTYPE HASHPREFIX(Create)(int numBuckets,
60 hashFunctionType fn, hashEqualityType eq,
63 , hashFreeData freeData
69 ht = xmalloc(sizeof(*ht));
70 ht->numBuckets = numBuckets;
71 ht->buckets = xcalloc(numBuckets, sizeof(*ht->buckets));
72 ht->freeKey = freeKey;
74 ht->freeData = freeData;
81 void HASHPREFIX(AddEntry)(HASHTYPE ht, HTKEYTYPE key
90 hash = ht->fn(key) % ht->numBuckets;
91 b = ht->buckets[hash];
93 while (b && b->key && ht->eq(b->key, key))
97 b = xmalloc(sizeof(*b));
103 b->next = ht->buckets[hash];
104 ht->buckets[hash] = b;
108 b->data = xrealloc(b->data, sizeof(*b->data) * (b->dataCount + 1));
109 b->data[b->dataCount++] = data;
113 HASHTYPE HASHPREFIX(Free)(HASHTYPE ht)
118 for (i = 0; i < ht->numBuckets; i++) {
122 ht->buckets[i] = NULL;
124 b->key = ht->freeKey(b->key);
132 for (j=0; j < b->dataCount; j++ ) {
133 b->data[j] = ht->freeData(b->data[j]);
136 b->data = _free(b->data);
140 } while ((b = n) != NULL);
143 ht->buckets = _free(ht->buckets);
149 int HASHPREFIX(HasEntry)(HASHTYPE ht, HTKEYTYPE key)
153 if (!(b = HASHPREFIX(findEntry)(ht, key))) return 0; else return 1;
158 int HASHPREFIX(GetEntry)(HASHTYPE ht, HTKEYTYPE key, HTDATATYPE** data,
159 int * dataCount, HTKEYTYPE* tableKey)
162 int rc = ((b = HASHPREFIX(findEntry)(ht, key)) != NULL);
165 *data = rc ? b->data : NULL;
167 *dataCount = rc ? b->dataCount : 0;
169 *tableKey = rc ? b->key : NULL;
174 void HASHPREFIX(PrintStats)(HASHTYPE ht) {
178 int hashcnt=0, bucketcnt=0, datacnt=0;
181 for (i=0; i<ht->numBuckets; i++) {
183 for (bucket=ht->buckets[i]; bucket; bucket=bucket->next){
186 datacnt += bucket->dataCount;
189 if (maxbuckets < buckets) maxbuckets = buckets;
190 if (buckets) hashcnt++;
191 bucketcnt += buckets;
193 fprintf(stderr, "Hashsize: %i\n", ht->numBuckets);
194 fprintf(stderr, "Hashbuckets: %i\n", hashcnt);
195 fprintf(stderr, "Keys: %i\n", bucketcnt);
196 fprintf(stderr, "Values: %i\n", datacnt);
197 fprintf(stderr, "Max Keys/Bucket: %i\n", maxbuckets);