Convert to new Doxygen style.
[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.7  2006/07/19 12:56:27  bernie
65  *#* Convert to new Doxygen style.
66  *#*
67  *#* Revision 1.6  2006/06/01 12:27:39  marco
68  *#* Added utilities for protocols
69  *#*
70  *#*/
71
72 #include "hashtable.h"
73 #include <cfg/debug.h>
74 #include <cfg/compiler.h>
75
76 #include <string.h>
77
78
79 #define ROTATE_LEFT_16(num, count)     (((num) << (count)) | ((num) >> (16-(count))))
80 #define ROTATE_RIGHT_16(num, count)    ROTATE_LEFT_16(num, 16-(count))
81
82 typedef const void** HashNodePtr;
83 #define NODE_EMPTY(node)               (!*(node))
84 #define HT_HAS_INTERNAL_KEY(ht)        (CONFIG_HT_OPTIONAL_INTERNAL_KEY && ht->flags.key_internal)
85
86 /** For hash tables with internal keys, compute the pointer to the internal key for a given \a node. */
87 INLINE uint8_t *key_internal_get_ptr(struct HashTable *ht, HashNodePtr node)
88 {
89         uint8_t* key_buf = ht->key_data.mem;
90         size_t index;
91
92         // Compute the index of the node and use it to move within the whole key buffer
93         index = node - &ht->mem[0];
94         ASSERT(index < (size_t)(1 << ht->max_elts_log2));
95         key_buf += index * (INTERNAL_KEY_MAX_LENGTH + 1);
96
97         return key_buf;
98 }
99
100
101 INLINE void node_get_key(struct HashTable* ht, HashNodePtr node, const void** key, uint8_t* key_length)
102 {
103         if (HT_HAS_INTERNAL_KEY(ht))
104         {
105                 uint8_t* k = key_internal_get_ptr(ht, node);
106
107                 // Key has its length stored in the first byte
108                 *key_length = *k++;
109                 *key = k;
110         }
111         else
112                 *key = ht->key_data.hook(*node, key_length);
113 }
114
115
116 INLINE bool node_key_match(struct HashTable* ht, HashNodePtr node, const void* key, uint8_t key_length)
117 {
118         const void* key2;
119         uint8_t key2_length;
120
121         node_get_key(ht, node, &key2, &key2_length);
122
123         return (key_length == key2_length && memcmp(key, key2, key_length) == 0);
124 }
125
126
127 static uint16_t calc_hash(const void* _key, uint8_t key_length)
128 {
129         const char* key = (const char*)_key;
130         uint16_t hash = key_length;
131         int i;
132         int len = (int)key_length;
133
134         for (i = 0; i < len; ++i)
135                 hash = ROTATE_LEFT_16(hash, 4) ^ key[i];
136
137         return hash ^ (hash >> 6) ^ (hash >> 13);
138 }
139
140
141 static HashNodePtr perform_lookup(struct HashTable* ht,
142                                   const void* key, uint8_t key_length)
143 {
144         uint16_t hash = calc_hash(key, key_length);
145         uint16_t mask = ((1 << ht->max_elts_log2) - 1);
146         uint16_t index = hash & mask;
147         uint16_t first_index = index;
148         uint16_t step;
149         HashNodePtr node;
150
151         // Fast-path optimization: we check immediately if the current node
152         //  is the one we were looking for, so we save the computation of the
153         //  increment step in the common case.
154         node = &ht->mem[index];
155         if (NODE_EMPTY(node)
156                 || node_key_match(ht, node, key, key_length))
157                 return node;
158
159         // Increment while going through the hash table in case of collision.
160         //  This implements the double-hash technique: we use the higher part
161         //  of the hash as a step increment instead of just going to the next
162         //  element, to minimize the collisions.
163         // Notice that the number must be odd to be sure that the whole table
164         //  is traversed. Actually MCD(table_size, step) must be 1, but
165         //  table_size is always a power of 2, so we just ensure that step is
166         //  never a multiple of 2.
167         step = (ROTATE_RIGHT_16(hash, ht->max_elts_log2) & mask) | 1;
168
169         do
170         {
171                 index += step;
172                 index &= mask;
173
174                 node = &ht->mem[index];
175                 if (NODE_EMPTY(node)
176                         || node_key_match(ht, node, key, key_length))
177                         return node;
178
179                 // The check is done after the key compare. This actually causes
180                 //  one more compare in the case the table is full (since the first
181                 //  element was compared at the very start, and then at the end),
182                 //  but it makes faster the common path where we enter this loop
183                 //  for the first time, and index will not match first_index for
184                 //  sure.
185         } while (index != first_index);
186
187         return NULL;
188 }
189
190
191 void ht_init(struct HashTable* ht)
192 {
193         memset(ht->mem, 0, sizeof(ht->mem[0]) * (1 << ht->max_elts_log2));
194 }
195
196
197 static bool insert(struct HashTable* ht, const void* key, uint8_t key_length, const void* data)
198 {
199         HashNodePtr node;
200
201         if (!data)
202                 return false;
203
204         if (HT_HAS_INTERNAL_KEY(ht))
205                 key_length = MIN(key_length, (uint8_t)INTERNAL_KEY_MAX_LENGTH);
206
207         node = perform_lookup(ht, key, key_length);
208         if (!node)
209                 return false;
210
211         if (HT_HAS_INTERNAL_KEY(ht))
212         {
213                 uint8_t* k = key_internal_get_ptr(ht, node);
214                 *k++ = key_length;
215                 memcpy(k, key, key_length);
216         }
217
218         *node = data;
219         return true;
220 }
221
222
223 bool ht_insert_with_key(struct HashTable* ht, const void* key, uint8_t key_length, const void* data)
224 {
225 #ifdef _DEBUG
226         if (!HT_HAS_INTERNAL_KEY(ht))
227         {
228                 // Construct a fake node and use it to match the key
229                 HashNodePtr node = &data;
230                 if (!node_key_match(ht, node, key, key_length))
231                 {
232                         ASSERT2(0, "parameter key is different from the external key");
233                         return false;
234                 }
235         }
236 #endif
237
238         return insert(ht, key, key_length, data);
239 }
240
241
242 bool ht_insert(struct HashTable* ht, const void* data)
243 {
244         const void* key;
245         uint8_t key_length;
246
247 #ifdef _DEBUG
248         if (HT_HAS_INTERNAL_KEY(ht))
249         {
250                 ASSERT("parameter cannot be a hash table with internal keys - use ht_insert_with_key()"
251                        && 0);
252                 return false;
253         }
254 #endif
255
256         key = ht->key_data.hook(data, &key_length);
257
258         return insert(ht, key, key_length, data);
259 }
260
261
262 const void* ht_find(struct HashTable* ht, const void* key, uint8_t key_length)
263 {
264         HashNodePtr node;
265
266         if (HT_HAS_INTERNAL_KEY(ht))
267                 key_length = MIN(key_length, (uint8_t)INTERNAL_KEY_MAX_LENGTH);
268
269         node = perform_lookup(ht, key, key_length);
270
271         if (!node || NODE_EMPTY(node))
272                 return NULL;
273
274         return *node;
275 }
276
277
278 #if 0
279
280 #include <stdlib.h>
281
282 bool ht_test(void);
283
284 static const void* test_get_key(const void* ptr, uint8_t* length)
285 {
286         const char* s = ptr;
287         *length = strlen(s);
288         return s;
289 }
290
291 #define NUM_ELEMENTS   256
292 DECLARE_HASHTABLE_STATIC(test1, 256, test_get_key);
293 DECLARE_HASHTABLE_INTERNALKEY_STATIC(test2, 256);
294
295 static char data[NUM_ELEMENTS][10];
296 static char keydomain[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
297
298 static bool single_test(void)
299 {
300         int i;
301
302         ht_init(&test1);
303         ht_init(&test2);
304
305         for (i=0;i<NUM_ELEMENTS;i++)
306         {
307                 int k;
308                 int klen;
309
310                 do
311                 {
312                         klen = (rand() % 8) + 1;
313                         for (k=0;k<klen;k++)
314                                 data[i][k] = keydomain[rand() % (sizeof(keydomain)-1)];
315                         data[i][k]=0;
316                 } while (ht_find_str(&test1, data[i]) != NULL);
317
318                 ASSERT(ht_insert(&test1, data[i]));
319                 ASSERT(ht_insert_str(&test2, data[i], data[i]));
320         }
321
322         for (i=0;i<NUM_ELEMENTS;i++)
323         {
324                 char *found1, *found2;
325
326                 found1 = (char*)ht_find_str(&test1, data[i]);
327                 if (strcmp(found1, data[i]) != 0)
328                 {
329                         ASSERT(strcmp(found1,data[i]) == 0);
330                         return false;
331                 }
332
333                 found2 = (char*)ht_find_str(&test2, data[i]);
334                 if (strcmp(found2, data[i]) != 0)
335                 {
336                         ASSERT(strcmp(found2,data[i]) == 0);
337                         return false;
338                 }
339         }
340
341         return true;
342 }
343
344 static uint16_t rand_seeds[] = { 1, 42, 666, 0xDEAD, 0xBEEF, 0x1337, 0xB00B };
345
346 bool ht_test(void)
347 {
348         int i;
349
350         for (i=0;i<countof(rand_seeds);++i)
351         {
352                 srand(rand_seeds[i]);
353                 if (!single_test())
354                 {
355                         kprintf("ht_test failed\n");
356                         return false;
357                 }
358         }
359
360         kprintf("ht_test successful\n");
361         return true;
362 }
363
364 #endif