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