695be32772a6b2ff029796237477399aaef1b546
[bertos.git] / bertos / struct / hashtable.h
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2004, 2006, 2008 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 2004 Giovanni Bajo
31  * -->
32  *
33  * \defgroup hashtable Hash table implementation
34  * \ingroup struct
35  * \{
36  *
37  * \brief Portable hash table
38  *
39  * This file implements a portable hash table, with the following features:
40  *
41  * \li Open double-hashing. The maximum number of elements is fixed. The double hashing
42  * function improves recovery in case of collisions.
43  * \li Configurable size (which is clamped to a power of two)
44  * \li Visiting interface through iterator (returns the element in random order).
45  * \li The key is stored within the data and a hook is used to extract it. Optionally, it
46  * is possible to store a copy of the key within the hash table.
47  *
48  * Since the hashing is open, there is no way to remove elements from the table. Instead, a
49  * function is provided to clear the table completely.
50  *
51  * The data stored within the table must be a pointer. The NULL pointer is used as
52  * a marker for a free node, so it is invalid to store a NULL pointer in the table
53  * with \c ht_insert().
54  *
55  * \author Giovanni Bajo <rasky@develer.com>
56  *
57  * $WIZ$ module_name = "hashtable"
58  * $WIZ$ module_configuration = "bertos/cfg/cfg_hashtable.h"
59  */
60
61 #ifndef STRUCT_HASHTABLE_H
62 #define STRUCT_HASHTABLE_H
63
64 #include "cfg/cfg_hashtable.h"
65
66 #include <cfg/compiler.h>
67 #include <cfg/macros.h>
68 #include <cfg/debug.h>
69
70 /// Maximum length of the internal key (use (2^n)-1 for slight speedup)
71 #define INTERNAL_KEY_MAX_LENGTH     15
72
73 /**
74  * Hook to get the key from \a data, which is an element of the hash table. The
75  * key must be returned together with \a key_length (in words).
76  */
77 typedef const void *(*hook_get_key)(const void *data, uint8_t *key_length);
78
79
80 /**
81  * Hash table description
82  *
83  * \note This structures MUST NOT be accessed directly. Its definition is
84  * provided in the header file only for optimization purposes (see the rationale
85  * in hashtable.c).
86  *
87  * \note If new elements must be added to this list, please double check
88  * \c DECLARE_HASHTABLE, which requires the existing elements to be at the top.
89  */
90 struct HashTable
91 {
92         const void **mem;            ///< Buckets of data
93         uint16_t max_elts_log2;      ///< Log2 of the size of the table
94         struct {
95                 bool key_internal : 1;   ///< true if the key is copied internally
96         } flags;
97         union {
98                 hook_get_key hook;       ///< Hook to get the key
99                 uint8_t *mem;            ///< Pointer to the key memory
100         } key_data;
101 };
102
103
104 /// Iterator to walk the hash table
105 typedef struct
106 {
107         const void** pos;
108         const void** end;
109 } HashIterator;
110
111
112 /**
113  * Declare a hash table in the current scope
114  *
115  * \param name Variable name
116  * \param size Number of elements
117  * \param hook_gk Hook to be used to extract the key from the node
118  *
119  * \note The number of elements will be rounded down to the nearest
120  * power of two.
121  *
122  */
123 #define DECLARE_HASHTABLE(name, size, hook_gk) \
124         static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
125         struct HashTable name = \
126                 { \
127                         .mem = name##_nodes, \
128                         .max_elts_log2 = UINT32_LOG2(size), \
129                         .flags = { .key_internal = false }, \
130                         .key_data.hook = hook_gk \
131                 }
132
133
134 /** Exactly like \c DECLARE_HASHTABLE, but the variable will be declared as static. */
135 #define DECLARE_HASHTABLE_STATIC(name, size, hook_gk) \
136         static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
137         static struct HashTable name = \
138                 { \
139                         .mem = name##_nodes, \
140                         .max_elts_log2 = UINT32_LOG2(size), \
141                         .flags = { .key_internal = false }, \
142                         .key_data.hook = hook_gk \
143                 }
144
145 #if CONFIG_HT_OPTIONAL_INTERNAL_KEY
146         /** Declare a hash table with internal copies of the keys. This version does not
147          *  require a hook, nor it requires the user to allocate static memory for the keys.
148          *  It is mostly suggested for tables whose keys are computed on the fly and need
149          *  to be stored somewhere.
150          */
151         #define DECLARE_HASHTABLE_INTERNALKEY(name, size) \
152                 static uint8_t name##_keys[(1 << UINT32_LOG2(size)) * (INTERNAL_KEY_MAX_LENGTH + 1)]; \
153                 static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
154                 struct HashTable name = { name##_nodes, UINT32_LOG2(size), { true }, name##_keys }
155
156         /** Exactly like \c DECLARE_HASHTABLE_INTERNALKEY, but the variable will be declared as static. */
157         #define DECLARE_HASHTABLE_INTERNALKEY_STATIC(name, size) \
158                 static uint8_t name##_keys[(1 << UINT32_LOG2(size)) * (INTERNAL_KEY_MAX_LENGTH + 1)]; \
159                 static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
160                 static struct HashTable name = \
161                         { \
162                                 .mem = name##_nodes, \
163                                 .max_elts_log2 = UINT32_LOG2(size), \
164                                 .flags = { .key_internal = true }, \
165                                 .key_data.mem = name##_keys \
166                         }
167 #endif
168
169 /**
170  * Initialize (and clear) a hash table in a memory buffer.
171  *
172  * \param ht Hash table declared with \c DECLARE_HASHTABLE
173  *
174  * \note This function must be called before using the hash table. Optionally,
175  * it can be called later in the program to clear the hash table,
176  * removing all its elements.
177  */
178 void ht_init(struct HashTable* ht);
179
180 /**
181  * Insert an element into the hash table
182  *
183  * \param ht Handle of the hash table
184  * \param data Data to be inserted into the table
185  * \return true if insertion was successful, false otherwise (table is full)
186  *
187  * \note The key for the element to insert is extract from the data with
188  * the hook. This means that this function cannot be called for hashtables
189  * with internal keys.
190  *
191  * \note If an element with the same key already exists in the table,
192  * it will be overwritten.
193  *
194  * \note It is not allowed to store NULL in the table. If you pass NULL as data,
195  * the function call will fail.
196  */
197 bool ht_insert(struct HashTable* ht, const void* data);
198
199 /**
200  * Insert an element into the hash table
201  *
202  * \param ht Handle of the hash table
203  * \param key Key of the element
204  * \param key_length Length of the key in characters
205  * \param data Data to be inserted into the table
206  * \return true if insertion was successful, false otherwise (table is full)
207  *
208  * \note If this function is called for hash table with external keys,
209  * the key provided must be match the key that would be extracted with the
210  * hook, otherwise the function will fail.
211  *
212  * \note If an element with the same key already exists in the table,
213  * it will be overwritten.
214  *
215  * \note It is not allowed to store NULL in the table. If you pass NULL as data,
216  * the function call will fail.
217  */
218 bool ht_insert_with_key(struct HashTable* ht, const void* key, uint8_t key_length, const void* data);
219
220 /**
221  * Find an element in the hash table
222  *
223  * \param ht Handle of the hash table
224  * \param key Key of the element
225  * \param key_length Length of the key in characters
226  * \return Data of the element, or NULL if no element was found for the given key.
227  */
228 const void* ht_find(struct HashTable* ht, const void* key, uint8_t key_length);
229
230 /** Similar to \c ht_insert_with_key() but \a key is an ASCIIZ string */
231 #define ht_insert_str(ht, key, data)         ht_insert_with_key(ht, key, strlen(key), data)
232
233 /** Similar to \c ht_find() but \a key is an ASCIIZ string */
234 #define ht_find_str(ht, key)                 ht_find(ht, key, strlen(key))
235
236 /// Get an iterator to the begin of the hash table \a ht
237 INLINE HashIterator ht_iter_begin(struct HashTable* ht)
238 {
239         HashIterator h;
240
241         h.pos = &ht->mem[0];
242         h.end = &ht->mem[1 << ht->max_elts_log2];
243
244         while (h.pos != h.end && !*h.pos)
245                 ++h.pos;
246
247         return h;
248 }
249
250 /**
251  * Get an iterator to the (exclusive) end of the hash table \a ht
252  *
253  * \note Like in STL, the end iterator is not a valid iterator (you
254  *       cannot call \c ht_iter_get() on it), and it must be used only to
255  *       detect if we reached the end of the iteration (through \c ht_iter_cmp()).
256  */
257 INLINE HashIterator ht_iter_end(struct HashTable* ht)
258 {
259         HashIterator h;
260
261         h.pos = h.end = &ht->mem[1 << ht->max_elts_log2];
262
263         return h;
264 }
265
266 /// Compare \a it1 and \a it2 for equality
267 INLINE bool ht_iter_cmp(HashIterator it1, HashIterator it2)
268 {
269         ASSERT(it1.end == it2.end);
270         return it1.pos == it2.pos;
271 }
272
273 /// Get the element within the hash table \a ht pointed by the iterator \a iter
274 INLINE const void* ht_iter_get(HashIterator iter)
275 { return *iter.pos; }
276
277 /** Return an iterator pointing to the element following \a h
278  *
279  * \note The order of the elements visited during the iteration is casual,
280  * and depends on the implementation.
281  *
282  */
283 INLINE HashIterator ht_iter_next(HashIterator h)
284 {
285         ++h.pos;
286         while (h.pos != h.end && !(*h.pos))
287                 ++h.pos;
288
289         return h;
290 }
291
292 int hashtable_testSetup(void);
293 int hashtable_testRun(void);
294 int hashtable_testTearDown(void);
295
296 /** \} */ // \defgroup hashtable
297
298 #endif /* STRUCT_HASHTABLE_H */