Line data Source code
1 : // SPDX-License-Identifier: BSD-2-Clause
2 : // Copyright (C) 2010 Andrea Mazzoleni
3 :
4 : /** \file
5 : * Fixed-size chained hashtable.
6 : *
7 : * This hashtable is a standard implementation of a chained hashtable with a fixed size.
8 : *
9 : * Note that performance starts to degenerate after reaching a load factor greater than 0.75.
10 : * The ::tommy_hashdyn and ::tommy_hashlin hashtables fix this problem growing dynamically.
11 : *
12 : * To initialize the hashtable you have to call tommy_hashtable_init() specifying
13 : * the fixed bucket size.
14 : *
15 : * \code
16 : * tommy_hashtable hashtable;
17 : *
18 : * tommy_hashtable_init(&hashtable, 1024);
19 : * \endcode
20 : *
21 : * To insert elements in the hashtable you have to call tommy_hashtable_insert() for
22 : * each element.
23 : * In the insertion call you have to specify the address of the node, the
24 : * address of the element, and the hash value of the key to use.
25 : * The address of the element is used to initialize the tommy_node::data field
26 : * of the node, and the hash to initialize the tommy_node::index field.
27 : *
28 : * \code
29 : * struct element {
30 : * int value;
31 : * // other fields
32 : * tommy_node node;
33 : * };
34 : *
35 : * struct element* elem = malloc(sizeof(struct element)); // creates the element
36 : *
37 : * elem->value = ...; // initializes the element
38 : *
39 : * tommy_hashtable_insert(&hashtable, &elem->node, elem, tommy_inthash_u32(elem->value)); // inserts the element
40 : * \endcode
41 : *
42 : * To find an element in the hashtable you have to call tommy_hashtable_search()
43 : * providing a comparison function, its argument, and the hash of the key to search.
44 : *
45 : * \code
46 : * int compare(const void* arg, const void* elem)
47 : * {
48 : * return *(const int*)arg != ((const struct element*)elem)->value;
49 : * }
50 : *
51 : * int value_to_find = 1;
52 : * struct element* elem = tommy_hashtable_search(&hashtable, compare, &value_to_find, tommy_inthash_u32(value_to_find));
53 : * if (!elem) {
54 : * // not found
55 : * } else {
56 : * // found
57 : * }
58 : * \endcode
59 : *
60 : * To iterate over all the elements in the hashtable with the same key, you have to
61 : * use tommy_hashtable_bucket() and follow the tommy_node::next pointer until 0.
62 : * You have also to check explicitly for the key, as the bucket may contain
63 : * different keys.
64 : *
65 : * \code
66 : * tommy_node* i = tommy_hashtable_bucket(&hashtable, tommy_inthash_u32(value_to_find));
67 : * while (i) {
68 : * struct element* elem = i->data; // gets the element pointer
69 : *
70 : * if (elem->value == value_to_find) {
71 : * printf("%d\n", elem->value); // process the element
72 : * }
73 : *
74 : * i = i->next; // goes to the next element
75 : * }
76 : * \endcode
77 : *
78 : * To remove an element from the hashtable you have to call tommy_hashtable_remove()
79 : * providing a comparison function, its argument, and the hash of the key to search
80 : * and remove.
81 : *
82 : * \code
83 : * struct element* elem = tommy_hashtable_remove(&hashtable, compare, &value_to_remove, tommy_inthash_u32(value_to_remove));
84 : * if (elem) {
85 : * free(elem); // frees the element allocated memory
86 : * }
87 : * \endcode
88 : *
89 : * To destroy the hashtable you have to remove all the elements, and deinitialize
90 : * the hashtable calling tommy_hashtable_done().
91 : *
92 : * \code
93 : * tommy_hashtable_done(&hashtable);
94 : * \endcode
95 : *
96 : * If you need to iterate over all the elements in the hashtable, you can use
97 : * tommy_hashtable_foreach() or tommy_hashtable_foreach_arg().
98 : * For traversal that permits insertions and removals, use tommy_hashtable_head()
99 : * and tommy_hashtable_next(), or tommy_hashtable_tail() and tommy_hashtable_prev().
100 : * Buckets are visited by increasing bucket index, and elements within each bucket
101 : * are visited in insertion order.
102 : *
103 : * \anchor tommy_hashtable_iterator_validity
104 : * Iterators are pointers to nodes currently contained in the hashtable.
105 : * Inserting elements or removing other nodes does not invalidate them or
106 : * change the relative iteration order of the remaining elements.
107 : * A forward or backward traversal visits every original element that remains
108 : * contained.
109 : * New elements can be visited if inserted after the current position in the
110 : * traversal direction; elements inserted before it need not be visited.
111 : *
112 : * Removing the pointed node invalidates its use as an iterator, even if its
113 : * storage has not been freed. Obtain the next or previous node before removal,
114 : * and keep that saved node contained until continuing the traversal.
115 : *
116 : * \code
117 : * tommy_hashtable_node* i = tommy_hashtable_head(&hashtable);
118 : * while (i) {
119 : * tommy_hashtable_node* next = tommy_hashtable_next(&hashtable, i);
120 : * if (should_remove(i->data)) {
121 : * free(tommy_hashtable_remove_existing(&hashtable, i));
122 : * }
123 : * i = next;
124 : * }
125 : * \endcode
126 : *
127 : * Changing a hash with tommy_hashtable_rehash_existing() can change iteration
128 : * order, so the traversal guarantee does not cover rehashing during traversal.
129 : * After swapping containers, use the container that now contains the node.
130 : * Clearing or deinitializing the container invalidates all its iterators.
131 : * Concurrent traversal and modification require external synchronization.
132 : *
133 : * Iterator calls follow node links directly without allocating memory.
134 : * Advancing within a bucket is O(1); crossing between buckets scans empty buckets.
135 : * Under suitable occupancy and distribution, each iterator step is expected O(1).
136 : * Sparse tables can result from a large initial allocation, removals,
137 : * tommy_hashtable_clear(), or tommy_hashtable_to_list().
138 : * A full traversal runs in O(n + b) time, where n is the number of elements
139 : * and b is the number of buckets.
140 : * Use foreach when no insertions or removals are needed.
141 : */
142 :
143 : #ifndef TOMMY_HASHTBL_H
144 : #define TOMMY_HASHTBL_H
145 :
146 : #include "tommyhash.h"
147 : #include "tommylist.h"
148 :
149 : /******************************************************************************/
150 : /* hashtable */
151 :
152 : /**
153 : * Hashtable node.
154 : * This is the node that you have to include inside your elements.
155 : */
156 : typedef tommy_node tommy_hashtable_node;
157 :
158 : /**
159 : * Hashtable container type.
160 : * \note Don't use internal fields directly, but access the container only using functions.
161 : */
162 : typedef struct tommy_hashtable_struct {
163 : tommy_hashtable_node** bucket; /**< Hash buckets. One list for each hash modulus. */
164 : tommy_size_t bucket_max; /**< Number of buckets. */
165 : tommy_size_t bucket_mask; /**< Bit mask to access the buckets. */
166 : tommy_size_t count; /**< Number of elements. */
167 : } tommy_hashtable;
168 :
169 : /**
170 : * Initializes the hashtable.
171 : * \param hashtable The hashtable.
172 : * \param bucket_max Minimum number of buckets to allocate. The effective number
173 : * is rounded up to a power of 2, with a minimum of 16 buckets.
174 : */
175 : TOMMY_API void tommy_hashtable_init(tommy_hashtable* hashtable, tommy_size_t bucket_max);
176 :
177 : /**
178 : * Deinitializes the hashtable.
179 : *
180 : * You can call this function with elements still contained,
181 : * but such elements are not going to be freed by this call.
182 : * \param hashtable The hashtable.
183 : */
184 : TOMMY_API void tommy_hashtable_done(tommy_hashtable* hashtable);
185 :
186 : /**
187 : * Exchanges the complete state of two initialized hashtables, including bucket allocations.
188 : * The hashtables must not share nodes. Nodes and elements are not accessed or modified.
189 : * Existing node pointers remain valid and belong to the other hashtable.
190 : * Passing the same hashtable twice has no effect. Both hashtables remain usable and deinitializable.
191 : * \param first The first hashtable.
192 : * \param second The second hashtable.
193 : * \note This operation is O(1) with respect to the number of elements.
194 : */
195 16 : tommy_inline void tommy_hashtable_swap(tommy_hashtable* first, tommy_hashtable* second)
196 : {
197 16 : tommy_hashtable tmp = *first;
198 16 : *first = *second;
199 16 : *second = tmp;
200 16 : }
201 :
202 : /**
203 : * Removes all elements, preserving the allocated buckets.
204 : * The hashtable remains initialized and can be reused immediately.
205 : * Elements are not freed and nodes are not accessed or modified.
206 : * Their links must not be used to traverse the previous contents.
207 : * You can call this function after tommy_hashtable_foreach() has freed the elements.
208 : * \param hashtable The hashtable.
209 : * \note This operation is O(b), where b is the number of buckets.
210 : */
211 : TOMMY_API void tommy_hashtable_clear(tommy_hashtable* hashtable);
212 :
213 : /**
214 : * Inserts an element in the hashtable.
215 : * \param hashtable The hashtable.
216 : * \param node Pointer to the node embedded into the element to insert.
217 : * \param data Pointer to the element to insert.
218 : * \param hash Hash of the element to insert.
219 : */
220 : TOMMY_API void tommy_hashtable_insert(tommy_hashtable* hashtable, tommy_hashtable_node* node, void* data, tommy_hash_t hash);
221 :
222 : /**
223 : * Inserts an element only if no equal element is already contained.
224 : * If found, the first equal element is returned,
225 : * and the hashtable and candidate node are left unchanged.
226 : * Otherwise, the candidate is inserted using the normal insertion policy,
227 : * and data is returned.
228 : * Elements are not freed by this call.
229 : * \param hashtable The hashtable.
230 : * \param node The candidate node. It must not belong to any container.
231 : * \param data Pointer to the element to insert.
232 : * \param cmp Compare function called with cmp_arg as first argument and with the element to compare as a second one.
233 : * The function should return 0 for equal elements, non-zero for different elements.
234 : * \param cmp_arg Compare argument describing the candidate key.
235 : * \param hash Hash of the candidate key, consistent with the comparison function.
236 : * \return The first equal element, or data if the candidate was inserted.
237 : */
238 : TOMMY_API void* tommy_hashtable_insert_unique(tommy_hashtable* hashtable, tommy_hashtable_node* node, void* data, tommy_search_func* cmp, const void* cmp_arg, tommy_hash_t hash);
239 :
240 : /**
241 : * Searches and removes an element from the hashtable.
242 : * You have to provide a compare function and the hash of the element you want to remove.
243 : * If the element is not found, 0 is returned.
244 : * If more equal elements are present, the first one is removed.
245 : * \param hashtable The hashtable.
246 : * \param cmp Compare function called with cmp_arg as first argument and with the element to compare as a second one.
247 : * The function should return 0 for equal elements, non-zero for different elements.
248 : * \param cmp_arg Compare argument passed as first argument of the compare function.
249 : * \param hash Hash of the element to find and remove.
250 : * \return The removed element, or 0 if not found.
251 : */
252 : TOMMY_API void* tommy_hashtable_remove(tommy_hashtable* hashtable, tommy_search_func* cmp, const void* cmp_arg, tommy_hash_t hash);
253 :
254 : /**
255 : * Gets the bucket of the specified hash.
256 : * The bucket is guaranteed to contain ALL the elements with the specified hash,
257 : * but it can also contain others.
258 : * You can access elements in the bucket following the tommy_node::next pointer until 0.
259 : * \param hashtable The hashtable.
260 : * \param hash Hash of the element to find.
261 : * \return The head of the bucket, or 0 if empty.
262 : */
263 11354 : tommy_inline tommy_hashtable_node* tommy_hashtable_bucket(tommy_hashtable* hashtable, tommy_hash_t hash)
264 : {
265 11354 : return hashtable->bucket[hash & hashtable->bucket_mask];
266 : }
267 :
268 : /**
269 : * Finds a node in the hashtable.
270 : * You have to provide a compare function and the hash of the element you want to find.
271 : * If more equal elements are present, the first one is returned.
272 : * \param hashtable The hashtable.
273 : * \param cmp Compare function called with cmp_arg as first argument and with the element to compare as a second one.
274 : * The function should return 0 for equal elements, non-zero for different elements.
275 : * \param cmp_arg Compare argument passed as first argument of the compare function.
276 : * \param hash Hash of the element to find.
277 : * \return The first node found, or 0 if none.
278 : */
279 9886 : tommy_inline tommy_hashtable_node* tommy_hashtable_find(tommy_hashtable* hashtable, tommy_search_func* cmp, const void* cmp_arg, tommy_hash_t hash)
280 : {
281 9886 : tommy_hashtable_node* i = tommy_hashtable_bucket(hashtable, hash);
282 :
283 424967 : while (i) {
284 : /* we first check if the hash matches, as in the same bucket we may have multiple hash values */
285 423871 : if (i->index == hash && cmp(cmp_arg, i->data) == 0)
286 8790 : return i;
287 415081 : i = i->next;
288 : }
289 1096 : return 0;
290 : }
291 :
292 : /**
293 : * Searches an element in the hashtable.
294 : * You have to provide a compare function and the hash of the element you want to find.
295 : * If more equal elements are present, the first one is returned.
296 : * \param hashtable The hashtable.
297 : * \param cmp Compare function called with cmp_arg as first argument and with the element to compare as a second one.
298 : * The function should return 0 for equal elements, non-zero for different elements.
299 : * \param cmp_arg Compare argument passed as first argument of the compare function.
300 : * \param hash Hash of the element to find.
301 : * \return The first element found, or 0 if none.
302 : */
303 8908 : tommy_inline void* tommy_hashtable_search(tommy_hashtable* hashtable, tommy_search_func* cmp, const void* cmp_arg, tommy_hash_t hash)
304 : {
305 8908 : tommy_hashtable_node* node = tommy_hashtable_find(hashtable, cmp, cmp_arg, hash);
306 :
307 8908 : return node ? node->data : 0;
308 : }
309 :
310 : /**
311 : * Removes an element from the hashtable.
312 : * You must already have the address of the node to remove.
313 : * \param hashtable The hashtable.
314 : * \param node The node to remove.
315 : * \return The removed element.
316 : */
317 : TOMMY_API void* tommy_hashtable_remove_existing(tommy_hashtable* hashtable, tommy_hashtable_node* node);
318 :
319 : /**
320 : * Gets the first node in iteration order, or 0 if empty.
321 : * See \ref tommy_hashtable_iterator_validity for ordering and iterator validity.
322 : * \param hashtable The hashtable.
323 : * \return The first node in iteration order, or 0 if empty.
324 : * \note This operation is expected O(1) under suitable occupancy and
325 : * distribution assumptions. In the worst case, scanning empty buckets takes
326 : * O(b), where b is the number of buckets.
327 : */
328 : TOMMY_API tommy_hashtable_node* tommy_hashtable_head(tommy_hashtable* hashtable);
329 :
330 : /**
331 : * Gets the last node in iteration order, or 0 if empty.
332 : * See \ref tommy_hashtable_iterator_validity for ordering and iterator validity.
333 : * \param hashtable The hashtable.
334 : * \return The last node in iteration order, or 0 if empty.
335 : * \note This operation is expected O(1) under suitable occupancy and
336 : * distribution assumptions. In the worst case, scanning empty buckets takes
337 : * O(b), where b is the number of buckets.
338 : */
339 : TOMMY_API tommy_hashtable_node* tommy_hashtable_tail(tommy_hashtable* hashtable);
340 :
341 : /**
342 : * Gets the following node in iteration order, or 0 for the tail.
343 : * See \ref tommy_hashtable_iterator_validity for ordering and iterator validity.
344 : * \param hashtable The hashtable.
345 : * \param node Node currently contained in the hashtable. It must not be 0.
346 : * \return The following node in iteration order, or 0 for the tail.
347 : * \note This operation is expected O(1) under suitable occupancy and
348 : * distribution assumptions. In the worst case, scanning empty buckets takes
349 : * O(b), where b is the number of buckets.
350 : */
351 : TOMMY_API tommy_hashtable_node* tommy_hashtable_next(tommy_hashtable* hashtable, tommy_hashtable_node* node);
352 :
353 : /**
354 : * Gets the preceding node in iteration order, or 0 for the head.
355 : * See \ref tommy_hashtable_iterator_validity for ordering and iterator validity.
356 : * \param hashtable The hashtable.
357 : * \param node Node currently contained in the hashtable. It must not be 0.
358 : * \return The preceding node in iteration order, or 0 for the head.
359 : * \note This operation is expected O(1) under suitable occupancy and
360 : * distribution assumptions. In the worst case, scanning empty buckets takes
361 : * O(b), where b is the number of buckets.
362 : */
363 : TOMMY_API tommy_hashtable_node* tommy_hashtable_prev(tommy_hashtable* hashtable, tommy_hashtable_node* node);
364 :
365 : /**
366 : * Updates the hash of an element already contained in the hashtable.
367 : * The node must belong to this hashtable. The caller updates the element key
368 : * and provides its new hash, without modifying tommy_node::index directly.
369 : * If the hash is unchanged, the node and its position are left unchanged.
370 : * Otherwise, the node is moved to the tail of the destination bucket,
371 : * even if the old and new hashes identify the same bucket.
372 : * The tommy_node::data field and the number of elements are left unchanged.
373 : * No memory allocation, deallocation or resize is performed.
374 : * Equal keys are allowed; no uniqueness check is performed.
375 : * \param hashtable The hashtable.
376 : * \param node The node whose hash is updated.
377 : * \param hash The new hash of the element.
378 : * \note This operation is O(1).
379 : */
380 : TOMMY_API void tommy_hashtable_rehash_existing(tommy_hashtable* hashtable, tommy_hashtable_node* node, tommy_hash_t hash);
381 :
382 : /**
383 : * Calls the specified function for each element in the hashtable.
384 : *
385 : * You cannot add or remove elements from the inside of the callback,
386 : * but can use it to deallocate them.
387 : *
388 : * \code
389 : * tommy_hashtable hashtable;
390 : *
391 : * // initializes the hashtable
392 : * tommy_hashtable_init(&hashtable, ...);
393 : *
394 : * ...
395 : *
396 : * // creates an element
397 : * struct element* elem = malloc(sizeof(struct element));
398 : *
399 : * ...
400 : *
401 : * // insert it in the hashtable
402 : * tommy_hashtable_insert(&hashtable, &elem->node, elem, tommy_inthash_u32(elem->value));
403 : *
404 : * ...
405 : *
406 : * // deallocates all the elements iterating the hashtable
407 : * tommy_hashtable_foreach(&hashtable, free);
408 : *
409 : * // deallocates the hashtable
410 : * tommy_hashtable_done(&hashtable);
411 : * \endcode
412 : *
413 : * If the callback frees the elements, the hashtable retains dangling
414 : * node pointers. Call tommy_hashtable_clear() before reusing it, or
415 : * tommy_hashtable_done() to release its storage.
416 : * \param hashtable The hashtable.
417 : * \param func Function to call with each element.
418 : */
419 : TOMMY_API void tommy_hashtable_foreach(tommy_hashtable* hashtable, tommy_foreach_func* func);
420 :
421 : /**
422 : * Calls the specified function with an argument for each element in the hashtable.
423 : * The iteration order and callback rules are the same as tommy_hashtable_foreach().
424 : * The callback may deallocate the current element.
425 : * Adding or removing elements from inside the callback is not allowed.
426 : * \param hashtable The hashtable.
427 : * \param func Function to call with each element.
428 : * \param arg Argument to pass to the function.
429 : */
430 : TOMMY_API void tommy_hashtable_foreach_arg(tommy_hashtable* hashtable, tommy_foreach_arg_func* func, void* arg);
431 :
432 : /**
433 : * Gets the number of elements.
434 : * \param hashtable The hashtable.
435 : * \return The number of elements in the hashtable.
436 : * \note This operation is O(1).
437 : */
438 17316 : tommy_inline tommy_size_t tommy_hashtable_count(const tommy_hashtable* hashtable)
439 : {
440 17316 : return hashtable->count;
441 : }
442 :
443 : /**
444 : * Checks whether the hashtable is empty.
445 : * \param hashtable The hashtable.
446 : * \return Nonzero if the hashtable is empty, 0 otherwise.
447 : * \note This operation is O(1).
448 : */
449 10 : tommy_inline tommy_bool_t tommy_hashtable_empty(const tommy_hashtable* hashtable)
450 : {
451 10 : return hashtable->count == 0;
452 : }
453 :
454 : /**
455 : * Gets the number of buckets.
456 : * \param hashtable The hashtable.
457 : * \return The number of buckets.
458 : * \note This operation is O(1).
459 : */
460 : tommy_inline tommy_size_t tommy_hashtable_bucket_count(const tommy_hashtable* hashtable)
461 : {
462 : return hashtable->bucket_max;
463 : }
464 :
465 : /**
466 : * Gets the size of allocated memory.
467 : * It includes the size of the ::tommy_hashtable_node of the stored elements.
468 : * \param hashtable The hashtable.
469 : * \return Total memory allocated by the hashtable, in bytes.
470 : */
471 : TOMMY_API tommy_size_t tommy_hashtable_memory_usage(const tommy_hashtable* hashtable);
472 :
473 : /**
474 : * Transfers all elements from the hashtable into a tommy_list.
475 : *
476 : * Removes every element from the \p hashtable and inserts them
477 : * into the provided \p list (at the tail), preserving the per-bucket order
478 : * but not guaranteeing any particular global order.
479 : *
480 : * After the call:
481 : * - the hashtable is left empty and initialized, preserving its allocated buckets
482 : * - the target list contains all the elements that were previously in the hashtable
483 : *
484 : * The tommy_node::data and tommy_node::index fields are left unchanged.
485 : *
486 : * This function is useful when you need to:
487 : * - extract all elements to process/sort them outside the hashtable
488 : * - convert the hashtable into a list for sequential iteration
489 : * - prepare for a full clear + re-insertion with different hash/ordering
490 : * - move ownership of the nodes to a list-based container
491 : *
492 : * Typical usage pattern:
493 : * \code
494 : * tommy_list all_elements;
495 : * tommy_list_init(&all_elements);
496 : *
497 : * // move everything out of the hashtable into the list
498 : * tommy_hashtable_to_list(&hashtable, &all_elements);
499 : *
500 : * // now you can sort, filter, process sequentially, etc.
501 : * tommy_list_sort(&all_elements, compare_by_value);
502 : * \endcode
503 : *
504 : * \param hashtable The hashtable to drain.
505 : * \param list The destination list. It must be initialized and must not share
506 : * nodes with the hashtable. Existing elements remain at the head of the list.
507 : * \note This operation is O(b), where b is the number of buckets.
508 : * \note No memory allocation or deallocation is performed.
509 : * \note The relative order of elements that were in the same bucket is preserved,
510 : * but the order among different buckets is bucket-order dependent.
511 : */
512 : TOMMY_API void tommy_hashtable_to_list(tommy_hashtable* hashtable, tommy_list* list);
513 :
514 : #endif
515 :
|