Debian Codegraph @

runtime/hashtable.c

raw
1 /* Copyright (C) 2004 Christopher Clark <[email protected]> */
2 /* taken from http://www.cl.cam.ac.uk/~cwc22/hashtable/ */
3
4 #include "hashtable_private.h"
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include <string.h>
8 #include <math.h>
9
10 /* this code has several warnings, but we ignore them because
11 * this seems to work and we do not want to engage in that code body. If
12 * we really run into troubles, it is better to change to libfastjson, which
13 * we should do in the medium to long term anyhow...
14 */
15 #ifdef __GNUC__
16 #pragma GCC diagnostic ignored "-Wredundant-decls"
17 #endif
18
19 /*
20 Credit for primes table: Aaron Krowne
21 http://br.endernet.org/~akrowne/
22 http://planetmath.org/encyclopedia/GoodHashTablePrimes.html
23 */
24 static const unsigned int primes[] = {53, 97, 193, 389, 769, 1543, 3079,
25 6151, 12289, 24593, 49157, 98317, 196613, 393241,
26 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653,
27 100663319, 201326611, 402653189, 805306457, 1610612741};
28 const unsigned int prime_table_length = sizeof(primes) / sizeof(primes[0]);
29
30 #define MAX_LOAD_FACTOR 65 /* to get real factor, divide by 100! */
31
32 /* compute max load. We use a constant factor of 0.65, but do
33 * everything times 100, so that we do not need floats.
34 */
35 static inline unsigned getLoadLimit(unsigned size) {
36 return (unsigned int)((unsigned long long)size * MAX_LOAD_FACTOR) / 100;
37 }
38
39 /*****************************************************************************/
40 struct hashtable *create_hashtable(unsigned int minsize,
41 unsigned int (*hashf)(void *),
42 int (*eqf)(void *, void *),
43 void (*dest)(void *)) {
44 struct hashtable *h;
45 unsigned int pindex, size = primes[0];
46 /* Check requested hashtable isn't too large */
47 if (minsize > (1u << 30)) return NULL;
48 /* Enforce size as prime */
49 for (pindex = 0; pindex < prime_table_length; pindex++) {
50 if (primes[pindex] > minsize) {
51 size = primes[pindex];
52 break;
53 }
54 }
55 h = (struct hashtable *)malloc(sizeof(struct hashtable));
56 if (NULL == h) return NULL; /*oom*/
57 h->table = (struct entry **)malloc(sizeof(struct entry *) * size);
58 if (NULL == h->table) {
59 free(h);
60 return NULL;
61 } /*oom*/
62 memset(h->table, 0, size * sizeof(struct entry *));
63 h->tablelength = size;
64 h->primeindex = pindex;
65 h->entrycount = 0;
66 h->hashfn = hashf;
67 h->eqfn = eqf;
68 h->dest = dest;
69 h->loadlimit = getLoadLimit(size);
70 return h;
71 }
72
73 /*****************************************************************************/
74 #if defined(__clang__)
75 #pragma GCC diagnostic ignored "-Wunknown-attributes"
76 #endif
77 unsigned int
78 #if defined(__clang__)
79 __attribute__((no_sanitize("unsigned-integer-overflow")))
80 #endif
81 hash(struct hashtable *h, void *k) {
82 /* Aim to protect against poor hash functions by adding logic here
83 * - logic taken from java 1.4 hashtable source */
84 unsigned int i = h->hashfn(k);
85 i += ~(i << 9);
86 i ^= ((i >> 14) | (i << 18)); /* >>> */
87 i += (i << 4);
88 i ^= ((i >> 10) | (i << 22)); /* >>> */
89 return i;
90 }
91
92 /*****************************************************************************/
93 static int hashtable_expand(struct hashtable *h) {
94 /* Double the size of the table to accomodate more entries */
95 struct entry **newtable;
96 struct entry *e;
97 struct entry **pE;
98 unsigned int newsize, i, idx;
99 /* Check we're not hitting max capacity */
100 if (h->primeindex == (prime_table_length - 1)) return 0;
101 newsize = primes[++(h->primeindex)];
102
103 newtable = (struct entry **)malloc(sizeof(struct entry *) * newsize);
104 if (NULL != newtable) {
105 memset(newtable, 0, newsize * sizeof(struct entry *));
106 /* This algorithm is not 'stable'. ie. it reverses the list
107 * when it transfers entries between the tables */
108 for (i = 0; i < h->tablelength; i++) {
109 while (NULL != (e = h->table[i])) {
110 h->table[i] = e->next;
111 idx = indexFor(newsize, e->h);
112 e->next = newtable[idx];
113 newtable[idx] = e;
114 }
115 }
116 free(h->table);
117 h->table = newtable;
118 }
119 /* Plan B: realloc instead */
120 else {
121 newtable = (struct entry **)realloc(h->table, newsize * sizeof(struct entry *));
122 if (NULL == newtable) {
123 (h->primeindex)--;
124 return 0;
125 }
126 h->table = newtable;
127 memset(&newtable[h->tablelength], 0, (newsize - h->tablelength) * sizeof(struct entry *));
128 for (i = 0; i < h->tablelength; i++) {
129 for (pE = &(newtable[i]), e = *pE; e != NULL; e = *pE) {
130 idx = indexFor(newsize, e->h);
131 if (idx == i) {
132 pE = &(e->next);
133 } else {
134 *pE = e->next;
135 e->next = newtable[idx];
136 newtable[idx] = e;
137 }
138 }
139 }
140 }
141 h->tablelength = newsize;
142 h->loadlimit = getLoadLimit(newsize);
143 return -1;
144 }
145
146 /*****************************************************************************/
147 unsigned int hashtable_count(struct hashtable *h) {
148 return h->entrycount;
149 }
150
151 /*****************************************************************************/
152 int hashtable_insert(struct hashtable *h, void *k, void *v) {
153 /* This method allows duplicate keys - but they shouldn't be used */
154 unsigned int idx;
155 struct entry *e;
156 if (++(h->entrycount) > h->loadlimit) {
157 /* Ignore the return value. If expand fails, we should
158 * still try cramming just this value into the existing table
159 * -- we may not have memory for a larger table, but one more
160 * element may be ok. Next time we insert, we'll try expanding again.*/
161 hashtable_expand(h);
162 }
163 e = (struct entry *)malloc(sizeof(struct entry));
164 if (NULL == e) {
165 --(h->entrycount);
166 return 0;
167 } /*oom*/
168 e->h = hash(h, k);
169 idx = indexFor(h->tablelength, e->h);
170 e->k = k;
171 e->v = v;
172 e->next = h->table[idx];
173 h->table[idx] = e;
174 return -1;
175 }
176
177 /*****************************************************************************/
178 void * /* returns value associated with key */
179 hashtable_search(struct hashtable *h, void *k) {
180 struct entry *e;
181 unsigned int hashvalue, idx;
182 hashvalue = hash(h, k);
183 idx = indexFor(h->tablelength, hashvalue);
184 e = h->table[idx];
185 while (NULL != e) {
186 /* Check hash value to short circuit heavier comparison */
187 if ((hashvalue == e->h) && (h->eqfn(k, e->k))) return e->v;
188 e = e->next;
189 }
190 return NULL;
191 }
192
193 /*****************************************************************************/
194 void * /* returns value associated with key */
195 hashtable_remove(struct hashtable *h, void *k) {
196 /* TODO: consider compacting the table when the load factor drops enough,
197 * or provide a 'compact' method. */
198
199 struct entry *e;
200 struct entry **pE;
201 void *v;
202 unsigned int hashvalue, idx;
203
204 hashvalue = hash(h, k);
205 idx = indexFor(h->tablelength, hash(h, k));
206 pE = &(h->table[idx]);
207 e = *pE;
208 while (NULL != e) {
209 /* Check hash value to short circuit heavier comparison */
210 if ((hashvalue == e->h) && (h->eqfn(k, e->k))) {
211 *pE = e->next;
212 h->entrycount--;
213 v = e->v;
214 freekey(e->k);
215 free(e);
216 return v;
217 }
218 pE = &(e->next);
219 e = e->next;
220 }
221 return NULL;
222 }
223
224 /*****************************************************************************/
225 /* destroy */
226 void hashtable_destroy(struct hashtable *h, int free_values) {
227 unsigned int i;
228 struct entry *e, *f;
229 struct entry **table = h->table;
230 if (free_values) {
231 for (i = 0; i < h->tablelength; i++) {
232 e = table[i];
233 while (NULL != e) {
234 f = e;
235 e = e->next;
236 freekey(f->k);
237 if (h->dest == NULL)
238 free(f->v);
239 else
240 h->dest(f->v);
241 free(f);
242 }
243 }
244 } else {
245 for (i = 0; i < h->tablelength; i++) {
246 e = table[i];
247 while (NULL != e) {
248 f = e;
249 e = e->next;
250 freekey(f->k);
251 free(f);
252 }
253 }
254 }
255 free(h->table);
256 free(h);
257 }
258
259 /* some generic hash functions */
260
261 /* one provided by Aaaron Wiebe based on perl's hashing algorithm
262 * (so probably pretty generic). Not for excessively large strings!
263 */
264 #if defined(__clang__)
265 #pragma GCC diagnostic ignored "-Wunknown-attributes"
266 #endif
267 unsigned __attribute__((nonnull(1))) int
268 #if defined(__clang__)
269 __attribute__((no_sanitize("unsigned-integer-overflow")))
270 #endif
271 hash_from_string(void *k) {
272 char *rkey = (char *)k;
273 unsigned hashval = 1;
274
275 while (*rkey) hashval = hashval * 33 + *rkey++;
276
277 return hashval;
278 }
279
280
281 int key_equals_string(void *key1, void *key2) {
282 /* we must return true IF the keys are equal! */
283 return !strcmp(key1, key2);
284 }
285
286
287 /*
288 * Copyright (c) 2002, Christopher Clark
289 * All rights reserved.
290 *
291 * Redistribution and use in source and binary forms, with or without
292 * modification, are permitted provided that the following conditions
293 * are met:
294 *
295 * * Redistributions of source code must retain the above copyright
296 * notice, this list of conditions and the following disclaimer.
297 *
298 * * Redistributions in binary form must reproduce the above copyright
299 * notice, this list of conditions and the following disclaimer in the
300 * documentation and/or other materials provided with the distribution.
301 *
302 * * Neither the name of the original author; nor the names of any contributors
303 * may be used to endorse or promote products derived from this software
304 * without specific prior written permission.
305 *
306 *
307 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
308 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
309 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
310 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
311 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
312 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
313 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
314 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
315 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
316 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
317 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
318 */