45bea14674024fd324253e6473661bcabc2e2843
[bertos.git] / mware / hashtable.h
1 /*!
2  * \file
3  * <!--
4  * Copyright 2004, 2006 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.7  2006/06/01 12:27:39  marco
35  *#* Added utilities for protocols
36  *#*
37  *#*/
38
39 #ifndef MWARE_HASHTABLE_H
40 #define MWARE_HASHTABLE_H
41
42 #include <cfg/compiler.h>
43 #include <cfg/macros.h>
44 #include <cfg/debug.h>
45
46 /*!
47  * Enable/disable support to declare special hash tables which maintain a copy of
48  * the key internally instead of relying on the hook to extract it from the data.
49  */
50 #define CONFIG_HT_OPTIONAL_INTERNAL_KEY      1
51
52 //! Maximum length of the internal key (use (2^n)-1 for slight speedup)
53 #define INTERNAL_KEY_MAX_LENGTH     15
54
55 /*!
56  * Hook to get the key from \a data, which is an element of the hash table. The
57  * key must be returned together with \a key_length (in words).
58  */
59 typedef const void *(*hook_get_key)(const void *data, uint8_t *key_length);
60
61
62 /*!
63  * Hash table description
64  *
65  * \note This structures MUST NOT be accessed directly. Its definition is
66  * provided in the header file only for optimization purposes (see the rationale
67  * in hashtable.c).
68  *
69  * \note If new elements must be added to this list, please double check
70  * \c DECLARE_HASHTABLE, which requires the existing elements to be at the top.
71  */
72 struct HashTable
73 {
74         const void **mem;            //!< Buckets of data
75         uint16_t max_elts_log2;      //!< Log2 of the size of the table
76         struct {
77                 bool key_internal : 1;   //!< true if the key is copied internally
78         } flags;
79         union {
80                 hook_get_key hook;       //!< Hook to get the key
81                 uint8_t *mem;            //!< Pointer to the key memory
82         } key_data;
83 };
84
85
86 //! Iterator to walk the hash table
87 typedef struct
88 {
89         const void** pos;
90         const void** end;
91 } HashIterator;
92
93
94 /*!
95  * Declare a hash table in the current scope
96  *
97  * \param name Variable name
98  * \param size Number of elements
99  * \param hook_gk Hook to be used to extract the key from the node
100  *
101  * \note The number of elements will be rounded down to the nearest
102  * power of two.
103  *
104  */
105 #define DECLARE_HASHTABLE(name, size, hook_gk) \
106         static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
107         struct HashTable name = { name##_nodes, UINT32_LOG2(size), { false }, hook_gk }
108
109 /*! Exactly like \c DECLARE_HASHTABLE, but the variable will be declared as static. */
110 #define DECLARE_HASHTABLE_STATIC(name, size, hook_gk) \
111         static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
112         static struct HashTable name = { name##_nodes, UINT32_LOG2(size), { false }, { hook_gk } }
113
114 #if CONFIG_HT_OPTIONAL_INTERNAL_KEY
115         /*! Declare a hash table with internal copies of the keys. This version does not
116          *  require a hook, nor it requires the user to allocate static memory for the keys.
117          *  It is mostly suggested for tables whose keys are computed on the fly and need
118          *  to be stored somewhere.
119          */
120         #define DECLARE_HASHTABLE_INTERNALKEY(name, size) \
121                 static uint8_t name##_keys[(1 << UINT32_LOG2(size)) * (INTERNAL_KEY_MAX_LENGTH + 1)]; \
122                 static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
123                 struct HashTable name = { name##_nodes, UINT32_LOG2(size), { true }, name##_keys }
124
125         /*! Exactly like \c DECLARE_HASHTABLE_INTERNALKEY, but the variable will be declared as static. */
126         #define DECLARE_HASHTABLE_INTERNALKEY_STATIC(name, size) \
127                 static uint8_t name##_keys[(1 << UINT32_LOG2(size)) * (INTERNAL_KEY_MAX_LENGTH + 1)]; \
128                 static const void* name##_nodes[1 << UINT32_LOG2(size)]; \
129                 static struct HashTable name = { name##_nodes, UINT32_LOG2(size), { true }, name##_keys }
130 #endif
131
132 /*!
133  * Initialize (and clear) a hash table in a memory buffer.
134  *
135  * \param ht Hash table declared with \c DECLARE_HASHTABLE
136  *
137  * \note This function must be called before using the hash table. Optionally,
138  * it can be called later in the program to clear the hash table, 
139  * removing all its elements.
140  */
141 void ht_init(struct HashTable* ht);
142
143 /*!
144  * Insert an element into the hash table
145  *
146  * \param ht Handle of the hash table
147  * \param data Data to be inserted into the table
148  * \return true if insertion was successful, false otherwise (table is full)
149  *
150  * \note The key for the element to insert is extract from the data with
151  * the hook. This means that this function cannot be called for hashtables
152  * with internal keys.
153  *
154  * \note If an element with the same key already exists in the table,
155  * it will be overwritten.
156  *
157  * \note It is not allowed to store NULL in the table. If you pass NULL as data,
158  * the function call will fail.
159  */
160 bool ht_insert(struct HashTable* ht, const void* data);
161
162 /*!
163  * Insert an element into the hash table
164  *
165  * \param ht Handle of the hash table
166  * \param key Key of the element
167  * \param key_length Length of the key in characters
168  * \param data Data to be inserted into the table
169  * \return true if insertion was successful, false otherwise (table is full)
170  *
171  * \note If this function is called for hash table with external keys,
172  * the key provided must be match the key that would be extracted with the
173  * hook, otherwise the function will fail.
174  *
175  * \note If an element with the same key already exists in the table,
176  * it will be overwritten.
177  *
178  * \note It is not allowed to store NULL in the table. If you pass NULL as data,
179  * the function call will fail.
180  */
181 bool ht_insert_with_key(struct HashTable* ht, const void* key, uint8_t key_length, const void* data);
182
183 /*!
184  * Find an element in the hash table
185  *
186  * \param ht Handle of the hash table
187  * \param key Key of the element
188  * \param key_length Length of the key in characters
189  * \return Data of the element, or NULL if no element was found for the given key.
190  */
191 const void* ht_find(struct HashTable* ht, const void* key, uint8_t key_length);
192
193 /*! Similar to \c ht_insert_with_key() but \a key is an ASCIIZ string */
194 #define ht_insert_str(ht, key, data)         ht_insert_with_key(ht, key, strlen(key), data)
195
196 /*! Similar to \c ht_find() but \a key is an ASCIIZ string */
197 #define ht_find_str(ht, key)                 ht_find(ht, key, strlen(key))
198
199 //! Get an iterator to the begin of the hash table \a ht
200 INLINE HashIterator ht_iter_begin(struct HashTable* ht)
201 {
202         HashIterator h;
203
204         h.pos = &ht->mem[0];
205         h.end = &ht->mem[1 << ht->max_elts_log2];
206
207         while (h.pos != h.end && !*h.pos)
208                 ++h.pos;
209
210         return h;
211 }
212
213 /*!
214  * Get an iterator to the (exclusive) end of the hash table \a ht
215  *
216  * \note Like in STL, the end iterator is not a valid iterator (you
217  *       cannot call \c ht_iter_get() on it), and it must be used only to
218  *       detect if we reached the end of the iteration (through \c ht_iter_cmp()).
219  */
220 INLINE HashIterator ht_iter_end(struct HashTable* ht)
221 {
222         HashIterator h;
223
224         h.pos = h.end = &ht->mem[1 << ht->max_elts_log2];
225
226         return h;
227 }
228
229 //! Compare \a it1 and \a it2 for equality
230 INLINE bool ht_iter_cmp(HashIterator it1, HashIterator it2)
231 {
232         ASSERT(it1.end == it2.end);
233         return it1.pos == it2.pos;
234 }
235
236 //! Get the element within the hash table \a ht pointed by the iterator \a iter
237 INLINE const void* ht_iter_get(HashIterator iter)
238 { return *iter.pos; }
239
240 /*! Return an iterator pointing to the element following \a h
241  *
242  * \note The order of the elements visited during the iteration is casual,
243  * and depends on the implementation.
244  *
245  */
246 INLINE HashIterator ht_iter_next(HashIterator h)
247 {
248         ++h.pos;
249         while (h.pos != h.end && !(*h.pos))
250                 ++h.pos;
251
252         return h;
253 }
254
255 #endif /* MWARE_HASHTABLE_H */