Implementazione di una tabella hash
[bertos.git] / mware / hashtable.h
1 /*!
2  * \file
3  * <!--
4  * Copyright (C) 2004 Giovanni Bajo
5  * Copyright (C) 2004 Develer S.r.l. (http://www.develer.com/)
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.1  2004/07/14 14:08:16  rasky
35  * Implementazione di una tabella hash
36  *
37  * Revision 1.10  2004/06/14 15:17:15  rasky
38  * Qualche fix alla documentazione Doxygen
39  *
40  * Revision 1.9  2004/06/14 15:15:24  rasky
41  * Cambiato key_data in un union invece di castare
42  * Aggiunto un ASSERT sull'indice calcolata nella key_internal_get_ptr
43  *
44  * Revision 1.8  2004/06/14 14:59:40  rasky
45  * Rinominanta la macro di configurazione per rispettare il namespace, e aggiunta in un punto in cui mancava
46  *
47  * Revision 1.7  2004/06/12 15:18:05  rasky
48  * Nuova hashtable con chiave esterna o interna a scelta, come discusso
49  *
50  * Revision 1.6  2004/05/26 16:33:31  rasky
51  * Aggiunta interfaccia per visita della hashtable tramite iteratori
52  *
53  * Revision 1.5  2004/05/24 18:42:23  rasky
54  * Fixato un commento doxygen
55  *
56  * Revision 1.4  2004/05/24 15:28:20  rasky
57  * Sistemata la documentazione, rimossa keycmp in favore della memcmp
58  *
59  */
60
61
62 #ifndef HASHTABLE_H
63 #define HASHTABLE_H
64
65 #include <compiler.h>
66 #include <kdebug.h>
67
68 /*! Enable/disable support to declare special hash tables which maintain a copy of
69  *  the key internally instead of relying on the hook to extract it from the data.
70  */
71 #define CONFIG_HT_OPTIONAL_INTERNAL_KEY      1
72
73 //! Maximum length of the internal key (use (2^n)-1 for slight speedup)
74 #define INTERNAL_KEY_MAX_LENGTH     15
75
76 /*! Hook to get the key from \a data, which is an element of the hash table. The
77  *  key must be returned together with \a key_length (in words).
78  */
79 typedef const void* (*hook_get_key)(const void* data, uint8_t* key_length);
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 //! Iterator to walk the hash table
104 typedef struct
105 {
106         const void** pos;
107         const void** end;
108 } HashIterator;
109
110 /*! Declare a hash table in the current scope
111  *
112  * \param name Variable name
113  * \param size Number of elements
114  * \param hook_gk Hook to be used to extract the key from the node
115  *
116  * \note The number of elements will be rounded down to the nearest
117  * power of two.
118  *
119  */
120 #define DECLARE_HASHTABLE(name, size, hook_gk) \
121         static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
122         struct HashTable name = { name##_nodes, UINT32_LOG2(size), { false }, hook_gk }
123
124 /*! Exactly like \c DECLARE_HASHTABLE, but the variable will be declared as static. */
125 #define DECLARE_HASHTABLE_STATIC(name, size, hook_gk) \
126         static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
127         static struct HashTable name = { name##_nodes, UINT32_LOG2(size), { false }, hook_gk }
128
129 #if CONFIG_HT_OPTIONAL_INTERNAL_KEY
130         /*! Declare a hash table with internal copies of the keys. This version does not
131          *  require a hook, nor it requires the user to allocate static memory for the keys.
132          *  It is mostly suggested for tables whose keys are computed on the fly and need
133          *  to be stored somewhere.
134          */
135         #define DECLARE_HASHTABLE_INTERNALKEY(name, size) \
136                 static uint8_t name##_keys[(1 << UINT32_LOG2(size)) * (INTERNAL_KEY_MAX_LENGTH + 1)]; \
137                 static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
138                 struct HashTable name = { name##_nodes, UINT32_LOG2(size), { true }, name##_keys }
139
140         /*! Exactly like \c DECLARE_HASHTABLE_INTERNALKEY, but the variable will be declared as static. */
141         #define DECLARE_HASHTABLE_INTERNALKEY_STATIC(name, size) \
142                 static uint8_t name##_keys[(1 << UINT32_LOG2(size)) * (INTERNAL_KEY_MAX_LENGTH + 1)]; \
143                 static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
144                 static struct HashTable name = { name##_nodes, UINT32_LOG2(size), { true }, name##_keys }
145 #endif
146
147 /*! Initialize (and clear) a hash table in a memory buffer.
148  *
149  * \param ht Hash table declared with \c DECLARE_HASHTABLE
150  *
151  * \note This function must be called before using the hash table. Optionally,
152  * it can be called later in the program to clear the hash table, 
153  * removing all its elements.
154  */
155 void ht_init(struct HashTable* ht);
156
157 /*! Insert an element into the hash table
158  *
159  * \param ht Handle of the hash table
160  * \param data Data to be inserted into the table
161  * \return true if insertion was successful, false otherwise (table is full)
162  *
163  * \note The key for the element to insert is extract from the data with
164  * the hook. This means that this function cannot be called for hashtables
165  * with internal keys.
166  *
167  * \note If an element with the same key already exists in the table,
168  * it will be overwritten.
169  *
170  * \note It is not allowed to store NULL in the table. If you pass NULL as data,
171  * the function call will fail.
172  */
173 bool ht_insert(struct HashTable* ht, const void* data);
174
175 /*! Insert an element into the hash table
176  *
177  * \param ht Handle of the hash table
178  * \param key Key of the element
179  * \param key_length Length of the key in characters
180  * \param data Data to be inserted into the table
181  * \return true if insertion was successful, false otherwise (table is full)
182  *
183  * \note If this function is called for hash table with external keys,
184  * the key provided must be match the key that would be extracted with the
185  * hook, otherwise the function will fail.
186  *
187  * \note If an element with the same key already exists in the table,
188  * it will be overwritten.
189  *
190  * \note It is not allowed to store NULL in the table. If you pass NULL as data,
191  * the function call will fail.
192  */
193 bool ht_insert_with_key(struct HashTable* ht, const void* key, uint8_t key_length, const void* data);
194
195 /*! Find an element in the hash table
196  *
197  * \param ht Handle of the hash table
198  * \param key Key of the element
199  * \param key_length Length of the key in characters
200  * \return Data of the element, or NULL if no element was found for the given key.
201  */
202 const void* ht_find(struct HashTable* ht, const void* key, uint8_t key_length);
203
204 /*! Similar to \c ht_insert_with_key() but \a key is an ASCIIZ string */
205 #define ht_insert_str(ht, key, data)         ht_insert_with_key(ht, key, strlen(key), data)
206
207 /*! Similar to \c ht_find() but \a key is an ASCIIZ string */
208 #define ht_find_str(ht, key)                 ht_find(ht, key, strlen(key))
209
210 //! Get an iterator to the begin of the hash table \a ht
211 INLINE HashIterator ht_iter_begin(struct HashTable* ht)
212 {
213         HashIterator h;
214
215         h.pos = &ht->mem[0];
216         h.end = &ht->mem[1 << ht->max_elts_log2];
217
218         while (h.pos != h.end && !*h.pos)
219                 ++h.pos;
220
221         return h;
222 }
223
224 /*! Get an iterator to the (exclusive) end of the hash table \a ht
225  *
226  *  \note Like in STL, the end iterator is not a valid iterator (you
227  *  cannot call \c ht_iter_get() on it), and it must be used only to
228  *  detect if we reached the end of the iteration (through \c ht_iter_cmp()).
229  */
230 INLINE HashIterator ht_iter_end(struct HashTable* ht)
231 {
232         HashIterator h;
233
234         h.pos = h.end = &ht->mem[1 << ht->max_elts_log2];
235
236         return h;
237 }
238
239 //! Compare \a it1 and \a it2 for equality
240 INLINE bool ht_iter_cmp(HashIterator it1, HashIterator it2)
241 {
242         ASSERT(it1.end == it2.end);
243         return it1.pos == it2.pos;
244 }
245
246 //! Get the element within the hash table \a ht pointed by the iterator \a iter
247 INLINE const void* ht_iter_get(HashIterator iter)
248 { return *iter.pos; }
249
250 /*! Return an iterator pointing to the element following \a h
251  *
252  * \note The order of the elements visited during the iteration is casual,
253  * and depends on the implementation.
254  *
255  */
256 INLINE HashIterator ht_iter_next(HashIterator h)
257 {
258         ++h.pos;
259         while (h.pos != h.end && !(*h.pos))
260                 ++h.pos;
261
262         return h;
263 }
264
265 #endif /* HASHTABLE_H */