1 /*
2  * Copyright (c) 2004, Stefan Walter
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  *     * Redistributions of source code must retain the above
10  *       copyright notice, this list of conditions and the
11  *       following disclaimer.
12  *     * Redistributions in binary form must reproduce the
13  *       above copyright notice, this list of conditions and
14  *       the following disclaimer in the documentation and/or
15  *       other materials provided with the distribution.
16  *     * The names of contributors to this software may not be
17  *       used to endorse or promote products derived from this
18  *       software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
31  * DAMAGE.
32  */
33 
34 /*
35  * Originally from apache 2.0
36  * Modifications for general use by <stef@memberwebs.com>
37  */
38 
39 /* Copyright 2000-2004 The Apache Software Foundation
40  *
41  * Licensed under the Apache License, Version 2.0 (the "License");
42  * you may not use this file except in compliance with the License.
43  * You may obtain a copy of the License at
44  *
45  *         http://www.apache.org/licenses/LICENSE-2.0
46  *
47  * Unless required by applicable law or agreed to in writing, software
48  * distributed under the License is distributed on an "AS IS" BASIS,
49  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
50  * See the License for the specific language governing permissions and
51  * limitations under the License.
52  */
53 
54 #include <sys/types.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include "hash.h"
58 
59 #define KEY_DATA(he)    ((he)->key)
60 
61 /*
62  * The internal form of a hash table.
63  *
64  * The table is an array indexed by the hash of the key; collisions
65  * are resolved by hanging a linked list of hash entries off each
66  * element of the array. Although this is a really simple design it
67  * isn't too bad given that pools have a low allocation overhead.
68  */
69 
70 typedef struct hsh_entry_t hsh_entry_t;
71 
72 struct hsh_entry_t
73 {
74     hsh_entry_t* next;
75     unsigned int hash;
76     const void* key;
77     size_t klen;
78     const void* val;
79 };
80 
81 /*
82  * Data structure for iterating through a hash table.
83  *
84  * We keep a pointer to the next hash entry here to allow the current
85  * hash entry to be freed or otherwise mangled between calls to
86  * hsh_next().
87  */
88 struct hsh_index_t
89 {
90     hsh_t* ht;
91     hsh_entry_t* ths;
92     hsh_entry_t* next;
93     unsigned int index;
94 };
95 
96 /*
97  * The size of the array is always a power of two. We use the maximum
98  * index rather than the size so that we can use bitwise-AND for
99  * modular arithmetic.
100  * The count of hash entries may be greater depending on the chosen
101  * collision rate.
102  */
103 struct hsh_t
104 {
105     hsh_entry_t** array;
106     hsh_index_t iterator;    /* For hsh_first(...) */
107     unsigned int count;
108     unsigned int max;
109 };
110 
111 
112 #define INITIAL_MAX 15 /* tunable == 2^n - 1 */
113 #define int_malloc malloc
114 #define int_calloc calloc
115 #define int_free free
116 
117 /*
118  * Hash creation functions.
119  */
120 
alloc_array(hsh_t * ht,unsigned int max)121 static hsh_entry_t** alloc_array(hsh_t* ht, unsigned int max)
122 {
123     return (hsh_entry_t**)int_calloc(sizeof(*(ht->array)), (max + 1));
124 }
125 
hsh_create()126 hsh_t* hsh_create()
127 {
128     hsh_t* ht = int_malloc(sizeof(hsh_t));
129     if(ht)
130     {
131         ht->count = 0;
132         ht->max = INITIAL_MAX;
133         ht->array = alloc_array(ht, ht->max);
134         if(!ht->array)
135         {
136             int_free(ht);
137             return NULL;
138         }
139     }
140     return ht;
141 }
142 
hsh_free(hsh_t * ht)143 void hsh_free(hsh_t* ht)
144 {
145     hsh_index_t* hi;
146 
147     for(hi = hsh_first(ht); hi; hi = hsh_next(hi))
148         int_free(hi->ths);
149 
150     if(ht->array)
151         int_free(ht->array);
152 
153     int_free(ht);
154 }
155 
156 /*
157  * Hash iteration functions.
158  */
159 
hsh_next(hsh_index_t * hi)160 hsh_index_t* hsh_next(hsh_index_t* hi)
161 {
162     hi->ths = hi->next;
163     while(!hi->ths)
164     {
165         if(hi->index > hi->ht->max)
166             return NULL;
167 
168         hi->ths = hi->ht->array[hi->index++];
169     }
170     hi->next = hi->ths->next;
171     return hi;
172 }
173 
hsh_first(hsh_t * ht)174 hsh_index_t* hsh_first(hsh_t* ht)
175 {
176     hsh_index_t* hi = &ht->iterator;
177 
178     hi->ht = ht;
179     hi->index = 0;
180     hi->ths = NULL;
181     hi->next = NULL;
182     return hsh_next(hi);
183 }
184 
hsh_this(hsh_index_t * hi,const void ** key,size_t * klen)185 void* hsh_this(hsh_index_t* hi, const void** key, size_t* klen)
186 {
187     if(key)
188         *key = KEY_DATA(hi->ths);
189     if(klen)
190         *klen = hi->ths->klen;
191     return (void*)hi->ths->val;
192 }
193 
194 
195 /*
196  * Expanding a hash table
197  */
198 
expand_array(hsh_t * ht)199 static int expand_array(hsh_t* ht)
200 {
201     hsh_index_t* hi;
202     hsh_entry_t** new_array;
203     unsigned int new_max;
204 
205     new_max = ht->max * 2 + 1;
206     new_array = alloc_array(ht, new_max);
207 
208     if(!new_array)
209         return 0;
210 
211     for(hi = hsh_first(ht); hi; hi = hsh_next(hi))
212     {
213         unsigned int i = hi->ths->hash & new_max;
214         hi->ths->next = new_array[i];
215         new_array[i] = hi->ths;
216     }
217 
218     if(ht->array)
219         free(ht->array);
220 
221     ht->array = new_array;
222     ht->max = new_max;
223     return 1;
224 }
225 
226 /*
227  * This is where we keep the details of the hash function and control
228  * the maximum collision rate.
229  *
230  * If val is non-NULL it creates and initializes a new hash entry if
231  * there isn't already one there; it returns an updatable pointer so
232  * that hash entries can be removed.
233  */
234 
find_entry(hsh_t * ht,const void * key,size_t klen,const void * val)235 static hsh_entry_t** find_entry(hsh_t* ht, const void* key, size_t klen, const void* val)
236 {
237     hsh_entry_t** hep;
238     hsh_entry_t* he;
239     const unsigned char* p;
240     unsigned int hash;
241     size_t i;
242 
243     /*
244      * This is the popular `times 33' hash algorithm which is used by
245      * perl and also appears in Berkeley DB. This is one of the best
246      * known hash functions for strings because it is both computed
247      * very fast and distributes very well.
248      *
249      * The originator may be Dan Bernstein but the code in Berkeley DB
250      * cites Chris Torek as the source. The best citation I have found
251      * is "Chris Torek, Hash function for text in C, Usenet message
252      * <27038@mimsy.umd.edu> in comp.lang.c , October, 1990." in Rich
253      * Salz's USENIX 1992 paper about INN which can be found at
254      * <http://citeseer.nj.nec.com/salz92internetnews.html>.
255      *
256      * The magic of number 33, i.e. why it works better than many other
257      * constants, prime or not, has never been adequately explained by
258      * anyone. So I try an explanation: if one experimentally tests all
259      * multipliers between 1 and 256 (as I did while writing a low-level
260      * data structure library some time ago) one detects that even
261      * numbers are not useable at all. The remaining 128 odd numbers
262      * (except for the number 1) work more or less all equally well.
263      * They all distribute in an acceptable way and this way fill a hash
264      * table with an average percent of approx. 86%.
265      *
266      * If one compares the chi^2 values of the variants (see
267      * Bob Jenkins ``Hashing Frequently Asked Questions'' at
268      * http://burtleburtle.net/bob/hash/hashfaq.html for a description
269      * of chi^2), the number 33 not even has the best value. But the
270      * number 33 and a few other equally good numbers like 17, 31, 63,
271      * 127 and 129 have nevertheless a great advantage to the remaining
272      * numbers in the large set of possible multipliers: their multiply
273      * operation can be replaced by a faster operation based on just one
274      * shift plus either a single addition or subtraction operation. And
275      * because a hash function has to both distribute good _and_ has to
276      * be very fast to compute, those few numbers should be preferred.
277      *
278      *                        -- Ralf S. Engelschall <rse@engelschall.com>
279      */
280     hash = 0;
281 
282     if(klen == HSH_KEY_STRING)
283     {
284         for(p = key; *p; p++)
285             hash = hash * 33 + *p;
286 
287         klen = p - (const unsigned char *)key;
288     }
289     else
290     {
291         for(p = key, i = klen; i; i--, p++)
292             hash = hash * 33 + *p;
293     }
294 
295     /* scan linked list */
296     for(hep = &ht->array[hash & ht->max], he = *hep;
297             he; hep = &he->next, he = *hep)
298     {
299      if(he->hash == hash &&
300         he->klen == klen &&
301         memcmp(KEY_DATA(he), key, klen) == 0)
302          break;
303     }
304 
305     if(he || !val)
306         return hep;
307 
308     /* add a new entry for non-NULL val */
309     he = int_malloc(sizeof(*he));
310 
311     if(he)
312     {
313         /* Key points to external data */
314         he->key = key;
315         he->klen = klen;
316 
317         he->next = NULL;
318         he->hash = hash;
319         he->val    = val;
320 
321         *hep = he;
322         ht->count++;
323     }
324 
325     return hep;
326 }
327 
hsh_get(hsh_t * ht,const void * key,size_t klen)328 void* hsh_get(hsh_t* ht, const void *key, size_t klen)
329 {
330         hsh_entry_t** he = find_entry(ht, key, klen, NULL);
331 
332         if(he && *he)
333             return (void*)((*he)->val);
334         else
335             return NULL;
336 }
337 
hsh_set(hsh_t * ht,const void * key,size_t klen,void * val)338 int hsh_set(hsh_t* ht, const void* key, size_t klen, void* val)
339 {
340     hsh_entry_t** hep = find_entry(ht, key, klen, val);
341 
342     if(hep && *hep)
343     {
344         /* replace entry */
345         (*hep)->val = val;
346 
347         /* check that the collision rate isn't too high */
348         if(ht->count > ht->max)
349         {
350             if(!expand_array(ht))
351                 return 0;
352         }
353 
354         return 1;
355     }
356 
357     return 0;
358 }
359 
hsh_rem(hsh_t * ht,const void * key,size_t klen)360 void* hsh_rem(hsh_t* ht, const void* key, size_t klen)
361 {
362     hsh_entry_t** hep = find_entry(ht, key, klen, NULL);
363     void* val = NULL;
364 
365     if(hep && *hep)
366     {
367         hsh_entry_t* old = *hep;
368         *hep = (*hep)->next;
369         --ht->count;
370         val = (void*)old->val;
371         free(old);
372     }
373 
374     return val;
375 }
376 
hsh_clear(hsh_t * ht)377 void hsh_clear(hsh_t* ht)
378 {
379 	hsh_entry_t *he, *next;
380 	int i;
381 
382 	/* Free all entries in the array */
383 	for (i = 0; i < ht->max; ++i) {
384 		he = ht->array[i];
385 		while (he) {
386 			next = he->next;
387 			free (he);
388 			he = next;
389 		}
390 	}
391 
392 	memset (ht->array, 0, ht->max * sizeof (hsh_entry_t*));
393 	ht->count = 0;
394 }
395 
hsh_count(hsh_t * ht)396 unsigned int hsh_count(hsh_t* ht)
397 {
398     return ht->count;
399 }
400 
401