Import changes from sc/firmware.
[bertos.git] / mware / hashtable.h
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
10  *
11  * This file implements a portable hash table, with the following features:
12  *
13  * \li Open double-hashing. The maximum number of elements is fixed. The double hashing
14  * function improves recovery in case of collisions.
15  * \li Configurable size (which is clamped to a power of two)
16  * \li Visiting interface through iterator (returns the element in random order).
17  * \li The key is stored within the data and a hook is used to extract it. Optionally, it
18  * is possible to store a copy of the key within the hash table.
19  *
20  * Since the hashing is open, there is no way to remove elements from the table. Instead, a
21  * function is provided to clear the table completely.
22  *
23  * The data stored within the table must be a pointer. The NULL pointer is used as
24  * a marker for a free node, so it is invalid to store a NULL pointer in the table
25  * with \c ht_insert().
26  *
27  * \version $Id$
28  *
29  * \author Giovanni Bajo <rasky@develer.com>
30  */
31
32 /*#*
33  *#* $Log$
34  *#* Revision 1.5  2004/10/03 20:43:22  bernie
35  *#* Import changes from sc/firmware.
36  *#*
37  *#* Revision 1.9  2004/06/14 15:15:24  rasky
38  *#* Cambiato key_data in un union invece di castare
39  *#* Aggiunto un ASSERT sull'indice calcolata nella key_internal_get_ptr
40  *#*
41  *#* Revision 1.8  2004/06/14 14:59:40  rasky
42  *#* Rinominanta la macro di configurazione per rispettare il namespace, e aggiunta in un punto in cui mancava
43  *#*
44  *#* Revision 1.7  2004/06/12 15:18:05  rasky
45  *#* Nuova hashtable con chiave esterna o interna a scelta, come discusso
46  *#*
47  *#* Revision 1.6  2004/05/26 16:33:31  rasky
48  *#* Aggiunta interfaccia per visita della hashtable tramite iteratori
49  *#*
50  *#* Revision 1.5  2004/05/24 18:42:23  rasky
51  *#* Fixato un commento doxygen
52  *#*
53  *#* Revision 1.4  2004/05/24 15:28:20  rasky
54  *#* Sistemata la documentazione, rimossa keycmp in favore della memcmp
55  *#*/
56
57 #ifndef MWARE_HASHTABLE_H
58 #define MWARE_HASHTABLE_H
59
60 #include <compiler.h>
61 #include <macros.h>
62 #include <debug.h>
63
64 /*!
65  * Enable/disable support to declare special hash tables which maintain a copy of
66  * the key internally instead of relying on the hook to extract it from the data.
67  */
68 #define CONFIG_HT_OPTIONAL_INTERNAL_KEY      1
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 = { name##_nodes, UINT32_LOG2(size), { false }, hook_gk }
126
127 /*! Exactly like \c DECLARE_HASHTABLE, but the variable will be declared as static. */
128 #define DECLARE_HASHTABLE_STATIC(name, size, hook_gk) \
129         static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
130         static struct HashTable name = { name##_nodes, UINT32_LOG2(size), { false }, hook_gk }
131
132 #if CONFIG_HT_OPTIONAL_INTERNAL_KEY
133         /*! Declare a hash table with internal copies of the keys. This version does not
134          *  require a hook, nor it requires the user to allocate static memory for the keys.
135          *  It is mostly suggested for tables whose keys are computed on the fly and need
136          *  to be stored somewhere.
137          */
138         #define DECLARE_HASHTABLE_INTERNALKEY(name, size) \
139                 static uint8_t name##_keys[(1 << UINT32_LOG2(size)) * (INTERNAL_KEY_MAX_LENGTH + 1)]; \
140                 static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
141                 struct HashTable name = { name##_nodes, UINT32_LOG2(size), { true }, name##_keys }
142
143         /*! Exactly like \c DECLARE_HASHTABLE_INTERNALKEY, but the variable will be declared as static. */
144         #define DECLARE_HASHTABLE_INTERNALKEY_STATIC(name, size) \
145                 static uint8_t name##_keys[(1 << UINT32_LOG2(size)) * (INTERNAL_KEY_MAX_LENGTH + 1)]; \
146                 static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
147                 static struct HashTable name = { name##_nodes, UINT32_LOG2(size), { true }, name##_keys }
148 #endif
149
150 /*!
151  * Initialize (and clear) a hash table in a memory buffer.
152  *
153  * \param ht Hash table declared with \c DECLARE_HASHTABLE
154  *
155  * \note This function must be called before using the hash table. Optionally,
156  * it can be called later in the program to clear the hash table, 
157  * removing all its elements.
158  */
159 void ht_init(struct HashTable* ht);
160
161 /*!
162  * Insert an element into the hash table
163  *
164  * \param ht Handle of the hash table
165  * \param data Data to be inserted into the table
166  * \return true if insertion was successful, false otherwise (table is full)
167  *
168  * \note The key for the element to insert is extract from the data with
169  * the hook. This means that this function cannot be called for hashtables
170  * with internal keys.
171  *
172  * \note If an element with the same key already exists in the table,
173  * it will be overwritten.
174  *
175  * \note It is not allowed to store NULL in the table. If you pass NULL as data,
176  * the function call will fail.
177  */
178 bool ht_insert(struct HashTable* ht, const void* data);
179
180 /*!
181  * Insert an element into the hash table
182  *
183  * \param ht Handle of the hash table
184  * \param key Key of the element
185  * \param key_length Length of the key in characters
186  * \param data Data to be inserted into the table
187  * \return true if insertion was successful, false otherwise (table is full)
188  *
189  * \note If this function is called for hash table with external keys,
190  * the key provided must be match the key that would be extracted with the
191  * hook, otherwise the function will fail.
192  *
193  * \note If an element with the same key already exists in the table,
194  * it will be overwritten.
195  *
196  * \note It is not allowed to store NULL in the table. If you pass NULL as data,
197  * the function call will fail.
198  */
199 bool ht_insert_with_key(struct HashTable* ht, const void* key, uint8_t key_length, const void* data);
200
201 /*!
202  * Find an element in the hash table
203  *
204  * \param ht Handle of the hash table
205  * \param key Key of the element
206  * \param key_length Length of the key in characters
207  * \return Data of the element, or NULL if no element was found for the given key.
208  */
209 const void* ht_find(struct HashTable* ht, const void* key, uint8_t key_length);
210
211 /*! Similar to \c ht_insert_with_key() but \a key is an ASCIIZ string */
212 #define ht_insert_str(ht, key, data)         ht_insert_with_key(ht, key, strlen(key), data)
213
214 /*! Similar to \c ht_find() but \a key is an ASCIIZ string */
215 #define ht_find_str(ht, key)                 ht_find(ht, key, strlen(key))
216
217 //! Get an iterator to the begin of the hash table \a ht
218 INLINE HashIterator ht_iter_begin(struct HashTable* ht)
219 {
220         HashIterator h;
221
222         h.pos = &ht->mem[0];
223         h.end = &ht->mem[1 << ht->max_elts_log2];
224
225         while (h.pos != h.end && !*h.pos)
226                 ++h.pos;
227
228         return h;
229 }
230
231 /*!
232  * Get an iterator to the (exclusive) end of the hash table \a ht
233  *
234  * \note Like in STL, the end iterator is not a valid iterator (you
235  *       cannot call \c ht_iter_get() on it), and it must be used only to
236  *       detect if we reached the end of the iteration (through \c ht_iter_cmp()).
237  */
238 INLINE HashIterator ht_iter_end(struct HashTable* ht)
239 {
240         HashIterator h;
241
242         h.pos = h.end = &ht->mem[1 << ht->max_elts_log2];
243
244         return h;
245 }
246
247 //! Compare \a it1 and \a it2 for equality
248 INLINE bool ht_iter_cmp(HashIterator it1, HashIterator it2)
249 {
250         ASSERT(it1.end == it2.end);
251         return it1.pos == it2.pos;
252 }
253
254 //! Get the element within the hash table \a ht pointed by the iterator \a iter
255 INLINE const void* ht_iter_get(HashIterator iter)
256 { return *iter.pos; }
257
258 /*! Return an iterator pointing to the element following \a h
259  *
260  * \note The order of the elements visited during the iteration is casual,
261  * and depends on the implementation.
262  *
263  */
264 INLINE HashIterator ht_iter_next(HashIterator h)
265 {
266         ++h.pos;
267         while (h.pos != h.end && !(*h.pos))
268                 ++h.pos;
269
270         return h;
271 }
272
273 #endif /* MWARE_HASHTABLE_H */