f95a7665af570f2b3654f5f7ca3be5294d057ab0
[bertos.git] / mware / hashtable.c
1 /**
2  * \file
3  * <!--
4  * Copyright 2004 Develer S.r.l. (http://www.develer.com/)
5  * Copyright 2004 Giovanni Bajo
6  * All Rights Reserved.
7  * -->
8  *
9  * \brief Portable hash table implementation
10  *
11  * Some rationales of our choices in implementation:
12  *
13  * \li For embedded systems, it is vital to allocate the table in static memory. To do
14  * so, it is necessary to expose the \c HashNode and \c HashTable structures in the header file.
15  * Nevertheless, they should be used as opaque types (that is, the users should not
16  * access the structure fields directly).
17  *
18  * \li To statically allocate the structures, a macro is provided. With this macro, we
19  * are hiding completely \c HashNode to the user (who only manipulates \c HashTable). Without
20  * the macro, the user would have had to define both the \c HashNode and the \c HashTable
21  * manually, and pass both of them to \c ht_init() (which would have created the link between
22  * the two). Instead, the link is created with a literal initialization.
23  *
24  * \li The hash table is created as power of two to remove the divisions from the code.
25  * Of course, hash functions work at their best when the table size is a prime number.
26  * When calculating the modulus to convert the hash value to an index, the actual operation
27  * becomes a bitwise AND: this is fast, but truncates the value losing bits. Thus, the higher
28  * bits are first "merged" with the lower bits through some XOR operations (see the last line of
29  * \c calc_hash()).
30  *
31  * \li To minimize the memory occupation, there is no flag to set for the empty node. An
32  * empty node is recognized by its data pointer set to NULL. It is then invalid to store
33  * NULL as data pointer in the table.
34  *
35  * \li The visiting interface through iterators is implemented with pass-by-value semantic.
36  * While this is overkill for medium-to-stupid compilers, it is the best designed from an
37  * user point of view. Moreover, being totally inlined (defined completely in the header),
38  * even a stupid compiler should be able to perform basic optimizations on it.
39  * We thought about using a pass-by-pointer semantic but it was much more awful to use, and
40  * the compiler is then forced to spill everything to the stack (unless it is *very* smart).
41  *
42  * \li The current implementation allows to either store the key internally (that is, copy
43  * the key within the hash table) or keep it external (that is, a hook is used to extract
44  * the key from the data in the node). The former is more memory-hungry of course, as it
45  * allocated static space to store the key copies. The overhead to keep both methods at
46  * the same time is minimal:
47  *    <ul>
48  *    <li>There is a run-time check in node_get_key which is execute per each node visited.</li>
49  *    <li>Theoretically, there is no memory overhead. In practice, there were no
50  *        flags in \c struct HashTable till now, so we had to add a first bit flag, but the
51  *        overhead will disappear if a second flag is added for a different reason later.</li>
52  *    <li>There is a little interface overhead, since we have two different versions of
53  *        \c ht_insert(), one with the key passed as parameter and one without, but in
54  *        the common case (external keys) both can be used.</li>
55  *    </ul>
56  *
57  * \version $Id$
58  *
59  * \author Giovanni Bajo <rasky@develer.com>
60  */
61
62 /*#*
63  *#* $Log$
64  *#* Revision 1.8  2007/02/06 16:05:01  asterix
65  *#* Replaced ROTATE_* with ROT* defined in macros.h
66  *#*
67  *#* Revision 1.7  2006/07/19 12:56:27  bernie
68  *#* Convert to new Doxygen style.
69  *#*
70  *#* Revision 1.6  2006/06/01 12:27:39  marco
71  *#* Added utilities for protocols
72  *#*
73  *#*/
74
75 #include "hashtable.h"
76 #include <cfg/debug.h>
77 #include <cfg/compiler.h>
78 #include <cfg/macros.h> //ROTL(), ROTR();
79
80 #include <string.h>
81
82
83
84 typedef const void** HashNodePtr;
85 #define NODE_EMPTY(node)               (!*(node))
86 #define HT_HAS_INTERNAL_KEY(ht)        (CONFIG_HT_OPTIONAL_INTERNAL_KEY && ht->flags.key_internal)
87
88 /** For hash tables with internal keys, compute the pointer to the internal key for a given \a node. */
89 INLINE uint8_t *key_internal_get_ptr(struct HashTable *ht, HashNodePtr node)
90 {
91         uint8_t* key_buf = ht->key_data.mem;
92         size_t index;
93
94         // Compute the index of the node and use it to move within the whole key buffer
95         index = node - &ht->mem[0];
96         ASSERT(index < (size_t)(1 << ht->max_elts_log2));
97         key_buf += index * (INTERNAL_KEY_MAX_LENGTH + 1);
98
99         return key_buf;
100 }
101
102
103 INLINE void node_get_key(struct HashTable* ht, HashNodePtr node, const void** key, uint8_t* key_length)
104 {
105         if (HT_HAS_INTERNAL_KEY(ht))
106         {
107                 uint8_t* k = key_internal_get_ptr(ht, node);
108
109                 // Key has its length stored in the first byte
110                 *key_length = *k++;
111                 *key = k;
112         }
113         else
114                 *key = ht->key_data.hook(*node, key_length);
115 }
116
117
118 INLINE bool node_key_match(struct HashTable* ht, HashNodePtr node, const void* key, uint8_t key_length)
119 {
120         const void* key2;
121         uint8_t key2_length;
122
123         node_get_key(ht, node, &key2, &key2_length);
124
125         return (key_length == key2_length && memcmp(key, key2, key_length) == 0);
126 }
127
128
129 static uint16_t calc_hash(const void* _key, uint8_t key_length)
130 {
131         const char* key = (const char*)_key;
132         uint16_t hash = key_length;
133         int i;
134         int len = (int)key_length;
135
136         for (i = 0; i < len; ++i)
137                 hash = ROTL(hash, 4) ^ key[i];
138
139         return hash ^ (hash >> 6) ^ (hash >> 13);
140 }
141
142
143 static HashNodePtr perform_lookup(struct HashTable* ht,
144                                   const void* key, uint8_t key_length)
145 {
146         uint16_t hash = calc_hash(key, key_length);
147         uint16_t mask = ((1 << ht->max_elts_log2) - 1);
148         uint16_t index = hash & mask;
149         uint16_t first_index = index;
150         uint16_t step;
151         HashNodePtr node;
152
153         // Fast-path optimization: we check immediately if the current node
154         //  is the one we were looking for, so we save the computation of the
155         //  increment step in the common case.
156         node = &ht->mem[index];
157         if (NODE_EMPTY(node)
158                 || node_key_match(ht, node, key, key_length))
159                 return node;
160
161         // Increment while going through the hash table in case of collision.
162         //  This implements the double-hash technique: we use the higher part
163         //  of the hash as a step increment instead of just going to the next
164         //  element, to minimize the collisions.
165         // Notice that the number must be odd to be sure that the whole table
166         //  is traversed. Actually MCD(table_size, step) must be 1, but
167         //  table_size is always a power of 2, so we just ensure that step is
168         //  never a multiple of 2.
169         step = (ROTR(hash, ht->max_elts_log2) & mask) | 1;
170
171         do
172         {
173                 index += step;
174                 index &= mask;
175
176                 node = &ht->mem[index];
177                 if (NODE_EMPTY(node)
178                         || node_key_match(ht, node, key, key_length))
179                         return node;
180
181                 // The check is done after the key compare. This actually causes
182                 //  one more compare in the case the table is full (since the first
183                 //  element was compared at the very start, and then at the end),
184                 //  but it makes faster the common path where we enter this loop
185                 //  for the first time, and index will not match first_index for
186                 //  sure.
187         } while (index != first_index);
188
189         return NULL;
190 }
191
192
193 void ht_init(struct HashTable* ht)
194 {
195         memset(ht->mem, 0, sizeof(ht->mem[0]) * (1 << ht->max_elts_log2));
196 }
197
198
199 static bool insert(struct HashTable* ht, const void* key, uint8_t key_length, const void* data)
200 {
201         HashNodePtr node;
202
203         if (!data)
204                 return false;
205
206         if (HT_HAS_INTERNAL_KEY(ht))
207                 key_length = MIN(key_length, (uint8_t)INTERNAL_KEY_MAX_LENGTH);
208
209         node = perform_lookup(ht, key, key_length);
210         if (!node)
211                 return false;
212
213         if (HT_HAS_INTERNAL_KEY(ht))
214         {
215                 uint8_t* k = key_internal_get_ptr(ht, node);
216                 *k++ = key_length;
217                 memcpy(k, key, key_length);
218         }
219
220         *node = data;
221         return true;
222 }
223
224
225 bool ht_insert_with_key(struct HashTable* ht, const void* key, uint8_t key_length, const void* data)
226 {
227 #ifdef _DEBUG
228         if (!HT_HAS_INTERNAL_KEY(ht))
229         {
230                 // Construct a fake node and use it to match the key
231                 HashNodePtr node = &data;
232                 if (!node_key_match(ht, node, key, key_length))
233                 {
234                         ASSERT2(0, "parameter key is different from the external key");
235                         return false;
236                 }
237         }
238 #endif
239
240         return insert(ht, key, key_length, data);
241 }
242
243
244 bool ht_insert(struct HashTable* ht, const void* data)
245 {
246         const void* key;
247         uint8_t key_length;
248
249 #ifdef _DEBUG
250         if (HT_HAS_INTERNAL_KEY(ht))
251         {
252                 ASSERT("parameter cannot be a hash table with internal keys - use ht_insert_with_key()"
253                        && 0);
254                 return false;
255         }
256 #endif
257
258         key = ht->key_data.hook(data, &key_length);
259
260         return insert(ht, key, key_length, data);
261 }
262
263
264 const void* ht_find(struct HashTable* ht, const void* key, uint8_t key_length)
265 {
266         HashNodePtr node;
267
268         if (HT_HAS_INTERNAL_KEY(ht))
269                 key_length = MIN(key_length, (uint8_t)INTERNAL_KEY_MAX_LENGTH);
270
271         node = perform_lookup(ht, key, key_length);
272
273         if (!node || NODE_EMPTY(node))
274                 return NULL;
275
276         return *node;
277 }
278
279
280 #if 0
281
282 #include <stdlib.h>
283
284 bool ht_test(void);
285
286 static const void* test_get_key(const void* ptr, uint8_t* length)
287 {
288         const char* s = ptr;
289         *length = strlen(s);
290         return s;
291 }
292
293 #define NUM_ELEMENTS   256
294 DECLARE_HASHTABLE_STATIC(test1, 256, test_get_key);
295 DECLARE_HASHTABLE_INTERNALKEY_STATIC(test2, 256);
296
297 static char data[NUM_ELEMENTS][10];
298 static char keydomain[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
299
300 static bool single_test(void)
301 {
302         int i;
303
304         ht_init(&test1);
305         ht_init(&test2);
306
307         for (i=0;i<NUM_ELEMENTS;i++)
308         {
309                 int k;
310                 int klen;
311
312                 do
313                 {
314                         klen = (rand() % 8) + 1;
315                         for (k=0;k<klen;k++)
316                                 data[i][k] = keydomain[rand() % (sizeof(keydomain)-1)];
317                         data[i][k]=0;
318                 } while (ht_find_str(&test1, data[i]) != NULL);
319
320                 ASSERT(ht_insert(&test1, data[i]));
321                 ASSERT(ht_insert_str(&test2, data[i], data[i]));
322         }
323
324         for (i=0;i<NUM_ELEMENTS;i++)
325         {
326                 char *found1, *found2;
327
328                 found1 = (char*)ht_find_str(&test1, data[i]);
329                 if (strcmp(found1, data[i]) != 0)
330                 {
331                         ASSERT(strcmp(found1,data[i]) == 0);
332                         return false;
333                 }
334
335                 found2 = (char*)ht_find_str(&test2, data[i]);
336                 if (strcmp(found2, data[i]) != 0)
337                 {
338                         ASSERT(strcmp(found2,data[i]) == 0);
339                         return false;
340                 }
341         }
342
343         return true;
344 }
345
346 static uint16_t rand_seeds[] = { 1, 42, 666, 0xDEAD, 0xBEEF, 0x1337, 0xB00B };
347
348 bool ht_test(void)
349 {
350         int i;
351
352         for (i=0;i<countof(rand_seeds);++i)
353         {
354                 srand(rand_seeds[i]);
355                 if (!single_test())
356                 {
357                         kprintf("ht_test failed\n");
358                         return false;
359                 }
360         }
361
362         kprintf("ht_test successful\n");
363         return true;
364 }
365
366 #endif