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