3 Troy D. Hanson, Arthur O'Dwyer
6 To download uthash, follow this link back to the
7 https://github.com/troydhanson/uthash[GitHub project page].
8 Back to my http://troydhanson.github.io/[other projects].
12 This document is written for C programmers. Since you're reading this, chances
13 are that you know a hash is used for looking up items using a key. In scripting
14 languages, hashes or "dictionaries" are used all the time. In C, hashes don't
15 exist in the language itself. This software provides a hash table for C
20 This software supports these operations on items in a hash table:
31 Add, find and delete are normally constant-time operations. This is influenced
32 by your key domain and the hash function.
34 This hash aims to be minimalistic and efficient. It's around 1000 lines of C.
35 It inlines automatically because it's implemented as macros. It's fast as long
36 as the hash function is suited to your keys. You can use the default hash
37 function, or easily compare performance and choose from among several other
38 <<hash_functions,built-in hash functions>>.
42 No, it's just a single header file: `uthash.h`. All you need to do is copy
43 the header file into your project, and:
47 Since uthash is a header file only, there is no library code to link against.
51 This software can be used in C and C++ programs. It has been tested on:
54 * Windows using Visual Studio 2008 and 2010
62 To run the test suite, enter the `tests` directory. Then,
64 * on Unix platforms, run `make`
65 * on Windows, run the "do_tests_win32.cmd" batch file. (You may edit the
66 batch file if your Visual Studio is installed in a non-standard location).
70 This software is made available under the
71 link:license.html[revised BSD license].
72 It is free and open source.
76 Follow the links on https://github.com/troydhanson/uthash to clone uthash or get a zip file.
80 Please use the https://groups.google.com/d/forum/uthash[uthash Google Group] to
81 ask questions. You can email it at uthash@googlegroups.com.
85 You may submit pull requests through GitHub. However, the maintainers of uthash
86 value keeping it unchanged, rather than adding bells and whistles.
90 Three "extras" come with uthash. These provide lists, dynamic arrays and
93 * link:utlist.html[utlist.h] provides linked list macros for C structures.
94 * link:utarray.html[utarray.h] implements dynamic arrays using macros.
95 * link:utstring.html[utstring.h] implements a basic dynamic string.
99 I wrote uthash in 2004-2006 for my own purposes. Originally it was hosted on
100 SourceForge. Uthash was downloaded around 30,000 times between 2006-2013 then
101 transitioned to GitHub. It's been incorporated into commercial software,
102 academic research, and into other open-source software. It has also been added
103 to the native package repositories for a number of Unix-y distros.
105 When uthash was written, there were fewer options for doing generic hash tables
106 in C than exist today. There are faster hash tables, more memory-efficient hash
107 tables, with very different API's today. But, like driving a minivan, uthash is
108 convenient, and gets the job done for many purposes.
110 As of July 2016, uthash is maintained by Arthur O'Dwyer.
115 In uthash, a hash table is comprised of structures. Each structure represents a
116 key-value association. One or more of the structure fields constitute the key.
117 The structure pointer itself is the value.
119 .Defining a structure that can be hashed
120 ----------------------------------------------------------------------
126 UT_hash_handle hh; /* makes this structure hashable */
128 ----------------------------------------------------------------------
130 Note that, in uthash, your structure will never be moved or copied into another
131 location when you add it into a hash table. This means that you can keep other
132 data structures that safely point to your structure-- regardless of whether you
133 add or delete it from a hash table during your program's lifetime.
137 There are no restrictions on the data type or name of the key field. The key
138 can also comprise multiple contiguous fields, having any names and data types.
140 .Any data type... really?
141 *****************************************************************************
142 Yes, your key and structure can have any data type. Unlike function calls with
143 fixed prototypes, uthash consists of macros-- whose arguments are untyped-- and
144 thus able to work with any type of structure or key.
145 *****************************************************************************
149 As with any hash, every item must have a unique key. Your application must
150 enforce key uniqueness. Before you add an item to the hash table, you must
151 first know (if in doubt, check!) that the key is not already in use. You
152 can check whether a key already exists in the hash table using `HASH_FIND`.
156 The `UT_hash_handle` field must be present in your structure. It is used for
157 the internal bookkeeping that makes the hash work. It does not require
158 initialization. It can be named anything, but you can simplify matters by
159 naming it `hh`. This allows you to use the easier "convenience" macros to add,
160 find and delete items.
167 The hash handle consumes about 32 bytes per item on a 32-bit system, or 56 bytes
168 per item on a 64-bit system. The other overhead costs-- the buckets and the
169 table-- are negligible in comparison. You can use `HASH_OVERHEAD` to get the
170 overhead size, in bytes, for a hash table. See <<Macro_reference,Macro
175 Some have asked how uthash cleans up its internal memory. The answer is simple:
176 'when you delete the final item' from a hash table, uthash releases all the
177 internal memory associated with that hash table, and sets its pointer to NULL.
183 This section introduces the uthash macros by example. For a more succinct
184 listing, see <<Macro_reference,Macro Reference>>.
186 .Convenience vs. general macros:
187 *****************************************************************************
188 The uthash macros fall into two categories. The 'convenience' macros can be used
189 with integer, pointer or string keys (and require that you chose the conventional
190 name `hh` for the `UT_hash_handle` field). The convenience macros take fewer
191 arguments than the general macros, making their usage a bit simpler for these
192 common types of keys.
194 The 'general' macros can be used for any types of keys, or for multi-field keys,
195 or when the `UT_hash_handle` has been named something other than `hh`. These
196 macros take more arguments and offer greater flexibility in return. But if the
197 convenience macros suit your needs, use them-- your code will be more readable.
198 *****************************************************************************
202 Your hash must be declared as a `NULL`-initialized pointer to your structure.
204 struct my_struct *users = NULL; /* important! initialize to NULL */
208 Allocate and initialize your structure as you see fit. The only aspect
209 of this that matters to uthash is that your key must be initialized to
210 a unique value. Then call `HASH_ADD`. (Here we use the convenience macro
211 `HASH_ADD_INT`, which offers simplified usage for keys of type `int`).
213 .Add an item to a hash
214 ----------------------------------------------------------------------
215 void add_user(int user_id, char *name) {
218 s = malloc(sizeof(struct my_struct));
220 strcpy(s->name, name);
221 HASH_ADD_INT( users, id, s ); /* id: name of key field */
223 ----------------------------------------------------------------------
225 The first parameter to `HASH_ADD_INT` is the hash table, and the
226 second parameter is the 'name' of the key field. Here, this is `id`. The
227 last parameter is a pointer to the structure being added.
230 .Wait.. the field name is a parameter?
231 *******************************************************************************
232 If you find it strange that `id`, which is the 'name of a field' in the
233 structure, can be passed as a parameter, welcome to the world of macros. Don't
234 worry- the C preprocessor expands this to valid C code.
235 *******************************************************************************
237 Key must not be modified while in-use
238 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
239 Once a structure has been added to the hash, do not change the value of its key.
240 Instead, delete the item from the hash, change the key, and then re-add it.
244 In the example above, we didn't check to see if `user_id` was already a key
245 of some existing item in the hash. *If there's any chance that duplicate keys
246 could be generated by your program, you must explicitly check the uniqueness*
247 before adding the key to the hash. If the key is already in the hash, you can
248 simply modify the existing structure in the hash rather than adding the item.
249 'It is an error to add two items with the same key to the hash table'.
251 Let's rewrite the `add_user` function to check whether the id is in the hash.
252 Only if the id is not present in the hash, do we create the item and add it.
253 Otherwise we just modify the structure that already exists.
255 void add_user(int user_id, char *name) {
258 HASH_FIND_INT(users, &user_id, s); /* id already in the hash? */
260 s = (struct my_struct*)malloc(sizeof(struct my_struct));
262 HASH_ADD_INT( users, id, s ); /* id: name of key field */
264 strcpy(s->name, name);
268 Why doesn't uthash check key uniqueness for you? It saves the cost of a hash
269 lookup for those programs which don't need it- for example, programs whose keys
270 are generated by an incrementing, non-repeating counter.
272 However, if replacement is a common operation, it is possible to use the
273 `HASH_REPLACE` macro. This macro, before adding the item, will try to find an
274 item with the same key and delete it first. It also returns a pointer to the
275 replaced item, so the user has a chance to de-allocate its memory.
277 Passing the hash pointer into functions
278 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
279 In the example above `users` is a global variable, but what if the caller wanted
280 to pass the hash pointer 'into' the `add_user` function? At first glance it would
281 appear that you could simply pass `users` as an argument, but that won't work
285 void add_user(struct my_struct *users, int user_id, char *name) {
287 HASH_ADD_INT( users, id, s );
290 You really need to pass 'a pointer' to the hash pointer:
293 void add_user(struct my_struct **users, int user_id, char *name) { ...
295 HASH_ADD_INT( *users, id, s );
298 Note that we dereferenced the pointer in the `HASH_ADD` also.
300 The reason it's necessary to deal with a pointer to the hash pointer is simple:
301 the hash macros modify it (in other words, they modify the 'pointer itself' not
302 just what it points to).
307 `HASH_REPLACE` macros are equivalent to HASH_ADD macros except they attempt
308 to find and delete the item first. If it finds and deletes an item, it will
309 also return that items pointer as an output parameter.
314 To look up a structure in a hash, you need its key. Then call `HASH_FIND`.
315 (Here we use the convenience macro `HASH_FIND_INT` for keys of type `int`).
317 .Find a structure using its key
318 ----------------------------------------------------------------------
319 struct my_struct *find_user(int user_id) {
322 HASH_FIND_INT( users, &user_id, s ); /* s: output pointer */
325 ----------------------------------------------------------------------
327 Here, the hash table is `users`, and `&user_id` points to the key (an integer
328 in this case). Last, `s` is the 'output' variable of `HASH_FIND_INT`. The
329 final result is that `s` points to the structure with the given key, or
330 is `NULL` if the key wasn't found in the hash.
333 The middle argument is a 'pointer' to the key. You can't pass a literal key
334 value to `HASH_FIND`. Instead assign the literal value to a variable, and pass
335 a pointer to the variable.
340 To delete a structure from a hash, you must have a pointer to it. (If you only
341 have the key, first do a `HASH_FIND` to get the structure pointer).
343 .Delete an item from a hash
344 ----------------------------------------------------------------------
345 void delete_user(struct my_struct *user) {
346 HASH_DEL(users, user); /* user: pointer to deletee */
347 free(user); /* optional; it's up to you! */
349 ----------------------------------------------------------------------
351 Here again, `users` is the hash table, and `user` is a pointer to the
352 structure we want to remove from the hash.
354 uthash never frees your structure
355 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
356 Deleting a structure just removes it from the hash table-- it doesn't `free`
357 it. The choice of when to free your structure is entirely up to you; uthash
358 will never free your structure. For example when using `HASH_REPLACE` macros,
359 a replaced output argument is returned back, in order to make it possible for
360 the user to de-allocate it.
362 Delete can change the pointer
363 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
364 The hash table pointer (which initially points to the first item added to the
365 hash) can change in response to `HASH_DEL` (i.e. if you delete the first item
370 The `HASH_ITER` macro is a deletion-safe iteration construct which expands
371 to a simple 'for' loop.
373 .Delete all items from a hash
374 ----------------------------------------------------------------------
376 struct my_struct *current_user, *tmp;
378 HASH_ITER(hh, users, current_user, tmp) {
379 HASH_DEL(users,current_user); /* delete; users advances to next */
380 free(current_user); /* optional- if you want to free */
383 ----------------------------------------------------------------------
387 If you only want to delete all the items, but not free them or do any
388 per-element clean up, you can do this more efficiently in a single operation:
390 HASH_CLEAR(hh,users);
392 Afterward, the list head (here, `users`) will be set to `NULL`.
397 The number of items in the hash table can be obtained using `HASH_COUNT`:
399 .Count of items in the hash table
400 ----------------------------------------------------------------------
401 unsigned int num_users;
402 num_users = HASH_COUNT(users);
403 printf("there are %u users\n", num_users);
404 ----------------------------------------------------------------------
406 Incidentally, this works even the list (`users`, here) is `NULL`, in
407 which case the count is 0.
409 Iterating and sorting
410 ~~~~~~~~~~~~~~~~~~~~~
412 You can loop over the items in the hash by starting from the beginning and
413 following the `hh.next` pointer.
415 .Iterating over all the items in a hash
416 ----------------------------------------------------------------------
420 for(s=users; s != NULL; s=s->hh.next) {
421 printf("user id %d: name %s\n", s->id, s->name);
424 ----------------------------------------------------------------------
426 There is also an `hh.prev` pointer you could use to iterate backwards through
427 the hash, starting from any known item.
430 Deletion-safe iteration
431 ^^^^^^^^^^^^^^^^^^^^^^^
432 In the example above, it would not be safe to delete and free `s` in the body
433 of the 'for' loop, (because `s` is derefenced each time the loop iterates).
434 This is easy to rewrite correctly (by copying the `s->hh.next` pointer to a
435 temporary variable 'before' freeing `s`), but it comes up often enough that a
436 deletion-safe iteration macro, `HASH_ITER`, is included. It expands to a
437 `for`-loop header. Here is how it could be used to rewrite the last example:
439 struct my_struct *s, *tmp;
441 HASH_ITER(hh, users, s, tmp) {
442 printf("user id %d: name %s\n", s->id, s->name);
443 /* ... it is safe to delete and free s here */
446 .A hash is also a doubly-linked list.
447 *******************************************************************************
448 Iterating backward and forward through the items in the hash is possible
449 because of the `hh.prev` and `hh.next` fields. All the items in the hash can
450 be reached by repeatedly following these pointers, thus the hash is also a
452 *******************************************************************************
454 If you're using uthash in a C++ program, you need an extra cast on the `for`
455 iterator, e.g., `s=(struct my_struct*)s->hh.next`.
459 The items in the hash are visited in "insertion order" when you follow the
460 `hh.next` pointer. You can sort the items into a new order using `HASH_SORT`.
462 HASH_SORT( users, name_sort );
464 The second argument is a pointer to a comparison function. It must accept two
465 pointer arguments (the items to compare), and must return an `int` which is
466 less than zero, zero, or greater than zero, if the first item sorts before,
467 equal to, or after the second item, respectively. (This is the same convention
468 used by `strcmp` or `qsort` in the standard C library).
470 int sort_function(void *a, void *b) {
471 /* compare a to b (cast a and b appropriately)
472 * return (int) -1 if (a < b)
473 * return (int) 0 if (a == b)
474 * return (int) 1 if (a > b)
478 Below, `name_sort` and `id_sort` are two examples of sort functions.
480 .Sorting the items in the hash
481 ----------------------------------------------------------------------
482 int name_sort(struct my_struct *a, struct my_struct *b) {
483 return strcmp(a->name,b->name);
486 int id_sort(struct my_struct *a, struct my_struct *b) {
487 return (a->id - b->id);
490 void sort_by_name() {
491 HASH_SORT(users, name_sort);
495 HASH_SORT(users, id_sort);
497 ----------------------------------------------------------------------
499 When the items in the hash are sorted, the first item may change position. In
500 the example above, `users` may point to a different structure after calling
506 We'll repeat all the code and embellish it with a `main()` function to form a
509 If this code was placed in a file called `example.c` in the same directory as
510 `uthash.h`, it could be compiled and run like this:
512 cc -o example example.c
515 Follow the prompts to try the program.
518 ----------------------------------------------------------------------
519 #include <stdio.h> /* gets */
520 #include <stdlib.h> /* atoi, malloc */
521 #include <string.h> /* strcpy */
527 UT_hash_handle hh; /* makes this structure hashable */
530 struct my_struct *users = NULL;
532 void add_user(int user_id, char *name) {
535 HASH_FIND_INT(users, &user_id, s); /* id already in the hash? */
537 s = (struct my_struct*)malloc(sizeof(struct my_struct));
539 HASH_ADD_INT( users, id, s ); /* id: name of key field */
541 strcpy(s->name, name);
544 struct my_struct *find_user(int user_id) {
547 HASH_FIND_INT( users, &user_id, s ); /* s: output pointer */
551 void delete_user(struct my_struct *user) {
552 HASH_DEL(users, user); /* user: pointer to deletee */
557 struct my_struct *current_user, *tmp;
559 HASH_ITER(hh, users, current_user, tmp) {
560 HASH_DEL(users, current_user); /* delete it (users advances to next) */
561 free(current_user); /* free it */
568 for(s=users; s != NULL; s=(struct my_struct*)(s->hh.next)) {
569 printf("user id %d: name %s\n", s->id, s->name);
573 int name_sort(struct my_struct *a, struct my_struct *b) {
574 return strcmp(a->name,b->name);
577 int id_sort(struct my_struct *a, struct my_struct *b) {
578 return (a->id - b->id);
581 void sort_by_name() {
582 HASH_SORT(users, name_sort);
586 HASH_SORT(users, id_sort);
589 int main(int argc, char *argv[]) {
596 printf(" 1. add user\n");
597 printf(" 2. add/rename user by id\n");
598 printf(" 3. find user\n");
599 printf(" 4. delete user\n");
600 printf(" 5. delete all users\n");
601 printf(" 6. sort items by name\n");
602 printf(" 7. sort items by id\n");
603 printf(" 8. print users\n");
604 printf(" 9. count users\n");
605 printf("10. quit\n");
610 add_user(id++, gets(in));
614 gets(in); id = atoi(in);
616 add_user(id, gets(in));
620 s = find_user(atoi(gets(in)));
621 printf("user: %s\n", s ? s->name : "unknown");
625 s = find_user(atoi(gets(in)));
626 if (s) delete_user(s);
627 else printf("id unknown\n");
642 num_users=HASH_COUNT(users);
643 printf("there are %u users\n", num_users);
651 delete_all(); /* free any structures */
654 ----------------------------------------------------------------------
656 This program is included in the distribution in `tests/example.c`. You can run
657 `make example` in that directory to compile it easily.
661 This section goes into specifics of how to work with different kinds of keys.
662 You can use nearly any type of key-- integers, strings, pointers, structures, etc.
666 ================================================================================
667 You can use floating point keys. This comes with the same caveats as with any
668 program that tests floating point equality. In other words, even the tiniest
669 difference in two floating point numbers makes them distinct keys.
670 ================================================================================
674 The preceding examples demonstrated use of integer keys. To recap, use the
675 convenience macros `HASH_ADD_INT` and `HASH_FIND_INT` for structures with
676 integer keys. (The other operations such as `HASH_DELETE` and `HASH_SORT` are
677 the same for all types of keys).
681 If your structure has a string key, the operations to use depend on whether your
682 structure 'points to' the key (`char *`) or the string resides `within` the
683 structure (`char a[10]`). *This distinction is important*. As we'll see below,
684 you need to use `HASH_ADD_KEYPTR` when your structure 'points' to a key (that is,
685 the key itself is 'outside' of the structure); in contrast, use `HASH_ADD_STR`
686 for a string key that is contained *within* your structure.
690 ================================================================================
691 The string is 'within' the structure in the first example below-- `name` is a
692 `char[10]` field. In the second example, the key is 'outside' of the
693 structure-- `name` is a `char *`. So the first example uses `HASH_ADD_STR` but
694 the second example uses `HASH_ADD_KEYPTR`. For information on this macro, see
695 the <<Macro_reference,Macro reference>>.
696 ================================================================================
698 String 'within' structure
699 ^^^^^^^^^^^^^^^^^^^^^^^^^
701 .A string-keyed hash (string within structure)
702 ----------------------------------------------------------------------
703 #include <string.h> /* strcpy */
704 #include <stdlib.h> /* malloc */
705 #include <stdio.h> /* printf */
709 char name[10]; /* key (string is WITHIN the structure) */
711 UT_hash_handle hh; /* makes this structure hashable */
715 int main(int argc, char *argv[]) {
716 const char **n, *names[] = { "joe", "bob", "betty", NULL };
717 struct my_struct *s, *tmp, *users = NULL;
720 for (n = names; *n != NULL; n++) {
721 s = (struct my_struct*)malloc(sizeof(struct my_struct));
722 strncpy(s->name, *n,10);
724 HASH_ADD_STR( users, name, s );
727 HASH_FIND_STR( users, "betty", s);
728 if (s) printf("betty's id is %d\n", s->id);
730 /* free the hash table contents */
731 HASH_ITER(hh, users, s, tmp) {
737 ----------------------------------------------------------------------
739 This example is included in the distribution in `tests/test15.c`. It prints:
743 String 'pointer' in structure
744 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
746 Now, here is the same example but using a `char *` key instead of `char [ ]`:
748 .A string-keyed hash (structure points to string)
749 ----------------------------------------------------------------------
750 #include <string.h> /* strcpy */
751 #include <stdlib.h> /* malloc */
752 #include <stdio.h> /* printf */
756 const char *name; /* key */
758 UT_hash_handle hh; /* makes this structure hashable */
762 int main(int argc, char *argv[]) {
763 const char **n, *names[] = { "joe", "bob", "betty", NULL };
764 struct my_struct *s, *tmp, *users = NULL;
767 for (n = names; *n != NULL; n++) {
768 s = (struct my_struct*)malloc(sizeof(struct my_struct));
771 HASH_ADD_KEYPTR( hh, users, s->name, strlen(s->name), s );
774 HASH_FIND_STR( users, "betty", s);
775 if (s) printf("betty's id is %d\n", s->id);
777 /* free the hash table contents */
778 HASH_ITER(hh, users, s, tmp) {
784 ----------------------------------------------------------------------
786 This example is included in `tests/test40.c`.
790 Your key can be a pointer. To be very clear, this means the 'pointer itself'
791 can be the key (in contrast, if the thing 'pointed to' is the key, this is a
792 different use case handled by `HASH_ADD_KEYPTR`).
794 Here is a simple example where a structure has a pointer member, called `key`.
797 ----------------------------------------------------------------------
809 char *someaddr = NULL;
813 el_t *e = (el_t*)malloc(sizeof(el_t));
815 e->key = (void*)someaddr;
817 HASH_ADD_PTR(hash,key,e);
818 HASH_FIND_PTR(hash, &someaddr, d);
819 if (d) printf("found\n");
826 ----------------------------------------------------------------------
828 This example is included in `tests/test57.c`. Note that the end of the program
829 deletes the element out of the hash, (and since no more elements remain in the
830 hash), uthash releases its internal memory.
834 Your key field can have any data type. To uthash, it is just a sequence of
835 bytes. Therefore, even a nested structure can be used as a key. We'll use the
836 general macros `HASH_ADD` and `HASH_FIND` to demonstrate.
838 NOTE: Structures contain padding (wasted internal space used to fulfill
839 alignment requirements for the members of the structure). These padding bytes
840 'must be zeroed' before adding an item to the hash or looking up an item.
841 Therefore always zero the whole structure before setting the members of
842 interest. The example below does this-- see the two calls to `memset`.
844 .A key which is a structure
845 ----------------------------------------------------------------------
857 /* ... other data ... */
861 int main(int argc, char *argv[]) {
862 record_t l, *p, *r, *tmp, *records = NULL;
864 r = (record_t*)malloc( sizeof(record_t) );
865 memset(r, 0, sizeof(record_t));
868 HASH_ADD(hh, records, key, sizeof(record_key_t), r);
870 memset(&l, 0, sizeof(record_t));
873 HASH_FIND(hh, records, &l.key, sizeof(record_key_t), p);
875 if (p) printf("found %c %d\n", p->key.a, p->key.b);
877 HASH_ITER(hh, records, p, tmp) {
878 HASH_DEL(records, p);
884 ----------------------------------------------------------------------
886 This usage is nearly the same as use of a compound key explained below.
888 Note that the general macros require the name of the `UT_hash_handle` to be
889 passed as the first argument (here, this is `hh`). The general macros are
890 documented in <<Macro_reference,Macro Reference>>.
897 Your key can even comprise multiple contiguous fields.
900 ----------------------------------------------------------------------
901 #include <stdlib.h> /* malloc */
902 #include <stddef.h> /* offsetof */
903 #include <stdio.h> /* printf */
904 #include <string.h> /* memset */
912 char encoding; /* these two fields */
913 int text[]; /* comprise the key */
921 int main(int argc, char *argv[]) {
923 msg_t *msg, *tmp, *msgs = NULL;
924 lookup_key_t *lookup_key;
926 int beijing[] = {0x5317, 0x4eac}; /* UTF-32LE for 北京 */
928 /* allocate and initialize our structure */
929 msg = (msg_t*)malloc( sizeof(msg_t) + sizeof(beijing) );
930 memset(msg, 0, sizeof(msg_t)+sizeof(beijing)); /* zero fill */
931 msg->len = sizeof(beijing);
932 msg->encoding = UTF32;
933 memcpy(msg->text, beijing, sizeof(beijing));
935 /* calculate the key length including padding, using formula */
936 keylen = offsetof(msg_t, text) /* offset of last key field */
937 + sizeof(beijing) /* size of last key field */
938 - offsetof(msg_t, encoding); /* offset of first key field */
940 /* add our structure to the hash table */
941 HASH_ADD( hh, msgs, encoding, keylen, msg);
943 /* look it up to prove that it worked :-) */
946 lookup_key = (lookup_key_t*)malloc(sizeof(*lookup_key) + sizeof(beijing));
947 memset(lookup_key, 0, sizeof(*lookup_key) + sizeof(beijing));
948 lookup_key->encoding = UTF32;
949 memcpy(lookup_key->text, beijing, sizeof(beijing));
950 HASH_FIND( hh, msgs, &lookup_key->encoding, keylen, msg );
951 if (msg) printf("found \n");
954 HASH_ITER(hh, msgs, msg, tmp) {
960 ----------------------------------------------------------------------
962 This example is included in the distribution in `tests/test22.c`.
964 If you use multi-field keys, recognize that the compiler pads adjacent fields
965 (by inserting unused space between them) in order to fulfill the alignment
966 requirement of each field. For example a structure containing a `char` followed
967 by an `int` will normally have 3 "wasted" bytes of padding after the char, in
968 order to make the `int` field start on a multiple-of-4 address (4 is the length
971 .Calculating the length of a multi-field key:
972 *******************************************************************************
973 To determine the key length when using a multi-field key, you must include any
974 intervening structure padding the compiler adds for alignment purposes.
976 An easy way to calculate the key length is to use the `offsetof` macro from
977 `<stddef.h>`. The formula is:
979 key length = offsetof(last_key_field)
980 + sizeof(last_key_field)
981 - offsetof(first_key_field)
983 In the example above, the `keylen` variable is set using this formula.
984 *******************************************************************************
986 When dealing with a multi-field key, you must zero-fill your structure before
987 `HASH_ADD`'ing it to a hash table, or using its fields in a `HASH_FIND` key.
989 In the previous example, `memset` is used to initialize the structure by
990 zero-filling it. This zeroes out any padding between the key fields. If we
991 didn't zero-fill the structure, this padding would contain random values. The
992 random values would lead to `HASH_FIND` failures; as two "identical" keys will
993 appear to mismatch if there are any differences within their padding.
996 Multi-level hash tables
997 ~~~~~~~~~~~~~~~~~~~~~~~
998 A multi-level hash table arises when each element of a hash table contains its
999 own secondary hash table. There can be any number of levels. In a scripting
1000 language you might see:
1004 The C program below builds this example in uthash: the hash table is called
1005 `items`. It contains one element (`bob`) whose own hash table contains one
1006 element (`age`) with value 37. No special functions are necessary to build
1007 a multi-level hash table.
1009 While this example represents both levels (`bob` and `age`) using the same
1010 structure, it would also be fine to use two different structure definitions.
1011 It would also be fine if there were three or more levels instead of two.
1013 .Multi-level hash table
1014 ----------------------------------------------------------------------
1020 /* hash of hashes */
1021 typedef struct item {
1030 int main(int argc, char *argvp[]) {
1031 item_t *item1, *item2, *tmp1, *tmp2;
1033 /* make initial element */
1034 item_t *i = malloc(sizeof(*i));
1035 strcpy(i->name, "bob");
1038 HASH_ADD_STR(items, name, i);
1040 /* add a sub hash table off this element */
1041 item_t *s = malloc(sizeof(*s));
1042 strcpy(s->name, "age");
1045 HASH_ADD_STR(i->sub, name, s);
1047 /* iterate over hash elements */
1048 HASH_ITER(hh, items, item1, tmp1) {
1049 HASH_ITER(hh, item1->sub, item2, tmp2) {
1050 printf("$items{%s}{%s} = %d\n", item1->name, item2->name, item2->val);
1054 /* clean up both hash tables */
1055 HASH_ITER(hh, items, item1, tmp1) {
1056 HASH_ITER(hh, item1->sub, item2, tmp2) {
1057 HASH_DEL(item1->sub, item2);
1060 HASH_DEL(items, item1);
1066 ----------------------------------------------------------------------
1067 The example above is included in `tests/test59.c`.
1070 Items in several hash tables
1071 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1072 A structure can be added to more than one hash table. A few reasons you might do
1075 - each hash table may use an alternative key;
1076 - each hash table may have its own sort order;
1077 - or you might simply use multiple hash tables for grouping purposes. E.g.,
1078 you could have users in an `admin_users` and a `users` hash table.
1080 Your structure needs to have a `UT_hash_handle` field for each hash table to
1081 which it might be added. You can name them anything. E.g.,
1083 UT_hash_handle hh1, hh2;
1085 Items with alternative keys
1086 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1087 You might create a hash table keyed on an ID field, and another hash table keyed
1088 on username (if usernames are unique). You can add the same user structure to
1089 both hash tables (without duplication of the structure), allowing lookup of a
1090 user structure by their name or ID. The way to achieve this is to have a
1091 separate `UT_hash_handle` for each hash to which the structure may be added.
1093 .A structure with two alternative keys
1094 ----------------------------------------------------------------------
1096 int id; /* usual key */
1097 char username[10]; /* alternative key */
1098 UT_hash_handle hh1; /* handle for first hash table */
1099 UT_hash_handle hh2; /* handle for second hash table */
1101 ----------------------------------------------------------------------
1103 In the example above, the structure can now be added to two separate hash
1104 tables. In one hash, `id` is its key, while in the other hash, `username` is
1105 its key. (There is no requirement that the two hashes have different key
1106 fields. They could both use the same key, such as `id`).
1108 Notice the structure has two hash handles (`hh1` and `hh2`). In the code
1109 below, notice that each hash handle is used exclusively with a particular hash
1110 table. (`hh1` is always used with the `users_by_id` hash, while `hh2` is
1111 always used with the `users_by_name` hash table).
1113 .Two keys on a structure
1114 ----------------------------------------------------------------------
1115 struct my_struct *users_by_id = NULL, *users_by_name = NULL, *s;
1119 s = malloc(sizeof(struct my_struct));
1121 strcpy(s->username, "thanson");
1123 /* add the structure to both hash tables */
1124 HASH_ADD(hh1, users_by_id, id, sizeof(int), s);
1125 HASH_ADD(hh2, users_by_name, username, strlen(s->username), s);
1127 /* lookup user by ID in the "users_by_id" hash table */
1129 HASH_FIND(hh1, users_by_id, &i, sizeof(int), s);
1130 if (s) printf("found id %d: %s\n", i, s->username);
1132 /* lookup user by username in the "users_by_name" hash table */
1134 HASH_FIND(hh2, users_by_name, name, strlen(name), s);
1135 if (s) printf("found user %s: %d\n", name, s->id);
1136 ----------------------------------------------------------------------
1139 Sorted insertion of new items
1140 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1141 If you would like to maintain a sorted hash you have two options. The first
1142 option is to use the HASH_SRT() macro, which will sort any unordered list in
1143 'O(n log(n))'. This is the best strategy if you're just filling up a hash
1144 table with items in random order with a single final HASH_SRT() operation
1145 when all is done. Obviously, this won't do what you want if you need
1146 the list to be in an ordered state at times between insertion of
1147 items. You can use HASH_SRT() after every insertion operation, but that will
1148 yield a computational complexity of 'O(n^2 log n)'.
1150 The second route you can take is via the in-order add and replace macros.
1151 The `HASH_ADD_INORDER*` macros work just like their `HASH_ADD*` counterparts, but
1152 with an additional comparison-function argument:
1154 int name_sort(struct my_struct *a, struct my_struct *b) {
1155 return strcmp(a->name,b->name);
1158 HASH_ADD_KEYPTR_INORDER(hh, items, &item->name, strlen(item->name), item, name_sort);
1160 New items are sorted at insertion time in 'O(n)', thus resulting in a
1161 total computational complexity of 'O(n^2)' for the creation of the hash
1162 table with all items.
1163 For in-order add to work, the list must be in an ordered state before
1164 insertion of the new item.
1168 It comes as no surprise that two hash tables can have different sort orders, but
1169 this fact can also be used advantageously to sort the 'same items' in several
1170 ways. This is based on the ability to store a structure in several hash tables.
1172 Extending the previous example, suppose we have many users. We have added each
1173 user structure to the `users_by_id` hash table and the `users_by_name` hash table.
1174 (To reiterate, this is done without the need to have two copies of each structure).
1175 Now we can define two sort functions, then use `HASH_SRT`.
1177 int sort_by_id(struct my_struct *a, struct my_struct *b) {
1178 if (a->id == b->id) return 0;
1179 return (a->id < b->id) ? -1 : 1;
1182 int sort_by_name(struct my_struct *a, struct my_struct *b) {
1183 return strcmp(a->username,b->username);
1186 HASH_SRT(hh1, users_by_id, sort_by_id);
1187 HASH_SRT(hh2, users_by_name, sort_by_name);
1189 Now iterating over the items in `users_by_id` will traverse them in id-order
1190 while, naturally, iterating over `users_by_name` will traverse them in
1191 name-order. The items are fully forward-and-backward linked in each order.
1192 So even for one set of users, we might store them in two hash tables to provide
1193 easy iteration in two different sort orders.
1195 Bloom filter (faster misses)
1196 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1197 Programs that generate a fair miss rate (`HASH_FIND` that result in `NULL`) may
1198 benefit from the built-in Bloom filter support. This is disabled by default,
1199 because programs that generate only hits would incur a slight penalty from it.
1200 Also, programs that do deletes should not use the Bloom filter. While the
1201 program would operate correctly, deletes diminish the benefit of the filter.
1202 To enable the Bloom filter, simply compile with `-DHASH_BLOOM=n` like:
1206 where the number can be any value up to 32 which determines the amount of memory
1207 used by the filter, as shown below. Using more memory makes the filter more
1208 accurate and has the potential to speed up your program by making misses bail
1211 .Bloom filter sizes for selected values of n
1212 [width="50%",cols="10m,30",grid="none",options="header"]
1213 |=====================================================================
1214 | n | Bloom filter size (per hash table)
1216 | 20 | 128 kilobytes
1219 | 32 | 512 megabytes
1220 |=====================================================================
1222 Bloom filters are only a performance feature; they do not change the results of
1223 hash operations in any way. The only way to gauge whether or not a Bloom filter
1224 is right for your program is to test it. Reasonable values for the size of the
1225 Bloom filter are 16-32 bits.
1229 An experimental 'select' operation is provided that inserts those items from a
1230 source hash that satisfy a given condition into a destination hash. This
1231 insertion is done with somewhat more efficiency than if this were using
1232 `HASH_ADD`, namely because the hash function is not recalculated for keys of the
1233 selected items. This operation does not remove any items from the source hash.
1234 Rather the selected items obtain dual presence in both hashes. The destination
1235 hash may already have items in it; the selected items are added to it. In order
1236 for a structure to be usable with `HASH_SELECT`, it must have two or more hash
1237 handles. (As described <<multihash,here>>, a structure can exist in many
1238 hash tables at the same time; it must have a separate hash handle for each one).
1240 user_t *users=NULL, *admins=NULL; /* two hash tables */
1244 UT_hash_handle hh; /* handle for users hash */
1245 UT_hash_handle ah; /* handle for admins hash */
1248 Now suppose we have added some users, and want to select just the administrator
1249 users who have id's less than 1024.
1251 #define is_admin(x) (((user_t*)x)->id < 1024)
1252 HASH_SELECT(ah,admins,hh,users,is_admin);
1254 The first two parameters are the 'destination' hash handle and hash table, the
1255 second two parameters are the 'source' hash handle and hash table, and the last
1256 parameter is the 'select condition'. Here we used a macro `is_admin()` but we
1257 could just as well have used a function.
1259 int is_admin(void *userv) {
1260 user_t *user = (user_t*)userv;
1261 return (user->id < 1024) ? 1 : 0;
1264 If the select condition always evaluates to true, this operation is
1265 essentially a 'merge' of the source hash into the destination hash. Of course,
1266 the source hash remains unchanged under any use of `HASH_SELECT`. It only adds
1267 items to the destination hash selectively.
1269 The two hash handles must differ. An example of using `HASH_SELECT` is included
1270 in `tests/test36.c`.
1274 Built-in hash functions
1275 ~~~~~~~~~~~~~~~~~~~~~~~
1276 Internally, a hash function transforms a key into a bucket number. You don't
1277 have to take any action to use the default hash function, currently Jenkin's.
1279 Some programs may benefit from using another of the built-in hash functions.
1280 There is a simple analysis utility included with uthash to help you determine
1281 if another hash function will give you better performance.
1283 You can use a different hash function by compiling your program with
1284 `-DHASH_FUNCTION=HASH_xyz` where `xyz` is one of the symbolic names listed
1287 cc -DHASH_FUNCTION=HASH_BER -o program program.c
1289 .Built-in hash functions
1290 [width="50%",cols="^5m,20",grid="none",options="header"]
1291 |===============================================================================
1293 |JEN | Jenkins (default)
1295 |SAX | Shift-Add-Xor
1296 |OAT | One-at-a-time
1297 |FNV | Fowler/Noll/Vo
1299 |MUR | MurmurHash v3 (see note)
1300 |===============================================================================
1304 ================================================================================
1305 A special symbol must be defined if you intend to use MurmurHash. To use it, add
1306 `-DHASH_USING_NO_STRICT_ALIASING` to your `CFLAGS`. And, if you are using
1307 the gcc compiler with optimization, add `-fno-strict-aliasing` to your `CFLAGS`.
1308 ================================================================================
1310 Which hash function is best?
1311 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1312 You can easily determine the best hash function for your key domain. To do so,
1313 you'll need to run your program once in a data-collection pass, and then run
1314 the collected data through an included analysis utility.
1316 First you must build the analysis utility. From the top-level directory,
1321 We'll use `test14.c` to demonstrate the data-collection and analysis steps
1322 (here using `sh` syntax to redirect file descriptor 3 to a file):
1325 --------------------------------------------------------------------------------
1326 % cc -DHASH_EMIT_KEYS=3 -I../src -o test14 test14.c
1327 % ./test14 3>test14.keys
1328 % ./keystats test14.keys
1329 fcn ideal% #items #buckets dup% fl add_usec find_usec del-all usec
1330 --- ------ ---------- ---------- ----- -- ---------- ---------- ------------
1331 SFH 91.6% 1219 256 0% ok 92 131 25
1332 FNV 90.3% 1219 512 0% ok 107 97 31
1333 SAX 88.7% 1219 512 0% ok 111 109 32
1334 OAT 87.2% 1219 256 0% ok 99 138 26
1335 JEN 86.7% 1219 256 0% ok 87 130 27
1336 BER 86.2% 1219 256 0% ok 121 129 27
1337 --------------------------------------------------------------------------------
1340 The number 3 in `-DHASH_EMIT_KEYS=3` is a file descriptor. Any file descriptor
1341 that your program doesn't use for its own purposes can be used instead of 3.
1342 The data-collection mode enabled by `-DHASH_EMIT_KEYS=x` should not be used in
1345 Usually, you should just pick the first hash function that is listed. Here, this
1346 is `SFH`. This is the function that provides the most even distribution for
1347 your keys. If several have the same `ideal%`, then choose the fastest one
1348 according to the `find_usec` column.
1350 keystats column reference
1351 ^^^^^^^^^^^^^^^^^^^^^^^^^
1353 symbolic name of hash function
1355 The percentage of items in the hash table which can be looked up within an
1356 ideal number of steps. (Further explained below).
1358 the number of keys that were read in from the emitted key file
1360 the number of buckets in the hash after all the keys were added
1362 the percent of duplicate keys encountered in the emitted key file.
1363 Duplicates keys are filtered out to maintain key uniqueness. (Duplicates
1364 are normal. For example, if the application adds an item to a hash,
1365 deletes it, then re-adds it, the key is written twice to the emitted file.)
1367 this is either `ok`, or `nx` (noexpand) if the expansion inhibited flag is
1368 set, described in <<expansion,Expansion internals>>. It is not recommended
1369 to use a hash function that has the `noexpand` flag set.
1371 the clock time in microseconds required to add all the keys to a hash
1373 the clock time in microseconds required to look up every key in the hash
1375 the clock time in microseconds required to delete every item in the hash
1382 *****************************************************************************
1383 The 'n' items in a hash are distributed into 'k' buckets. Ideally each bucket
1384 would contain an equal share '(n/k)' of the items. In other words, the maximum
1385 linear position of any item in a bucket chain would be 'n/k' if every bucket is
1386 equally used. If some buckets are overused and others are underused, the
1387 overused buckets will contain items whose linear position surpasses 'n/k'.
1388 Such items are considered non-ideal.
1390 As you might guess, `ideal%` is the percentage of ideal items in the hash. These
1391 items have favorable linear positions in their bucket chains. As `ideal%`
1392 approaches 100%, the hash table approaches constant-time lookup performance.
1393 *****************************************************************************
1398 NOTE: This utility is only available on Linux, and on FreeBSD (8.1 and up).
1400 A utility called `hashscan` is included in the `tests/` directory. It
1401 is built automatically when you run `make` in that directory. This tool
1402 examines a running process and reports on the uthash tables that it finds in
1403 that program's memory. It can also save the keys from each table in a format
1404 that can be fed into `keystats`.
1406 Here is an example of using `hashscan`. First ensure that it is built:
1411 Since `hashscan` needs a running program to inspect, we'll start up a simple
1412 program that makes a hash table and then sleeps as our test subject:
1417 Now that we have a test program, let's run `hashscan` on it:
1420 Address ideal items buckets mc fl bloom/sat fcn keys saved to
1421 ------------------ ----- -------- -------- -- -- --------- --- -------------
1422 0x862e038 81% 10000 4096 11 ok 16 14% JEN
1424 If we wanted to copy out all its keys for external analysis using `keystats`,
1428 Address ideal items buckets mc fl bloom/sat fcn keys saved to
1429 ------------------ ----- -------- -------- -- -- --------- --- -------------
1430 0x862e038 81% 10000 4096 11 ok 16 14% JEN /tmp/9711-0.key
1432 Now we could run `./keystats /tmp/9711-0.key` to analyze which hash function
1433 has the best characteristics on this set of keys.
1435 hashscan column reference
1436 ^^^^^^^^^^^^^^^^^^^^^^^^^
1438 virtual address of the hash table
1440 The percentage of items in the table which can be looked up within an ideal
1441 number of steps. See <<ideal>> in the `keystats` section.
1443 number of items in the hash table
1445 number of buckets in the hash table
1447 the maximum chain length found in the hash table (uthash usually tries to
1448 keep fewer than 10 items in each bucket, or in some cases a multiple of 10)
1450 flags (either `ok`, or `NX` if the expansion-inhibited flag is set)
1452 if the hash table uses a Bloom filter, this is the size (as a power of two)
1453 of the filter (e.g. 16 means the filter is 2^16 bits in size). The second
1454 number is the "saturation" of the bits expressed as a percentage. The lower
1455 the percentage, the more potential benefit to identify cache misses quickly.
1457 symbolic name of hash function
1459 file to which keys were saved, if any
1462 *****************************************************************************
1463 When hashscan runs, it attaches itself to the target process, which suspends
1464 the target process momentarily. During this brief suspension, it scans the
1465 target's virtual memory for the signature of a uthash hash table. It then
1466 checks if a valid hash table structure accompanies the signature and reports
1467 what it finds. When it detaches, the target process resumes running normally.
1468 The hashscan is performed "read-only"-- the target process is not modified.
1469 Since hashscan is analyzing a momentary snapshot of a running process, it may
1470 return different results from one run to another.
1471 *****************************************************************************
1476 Internally this hash manages the number of buckets, with the goal of having
1477 enough buckets so that each one contains only a small number of items.
1479 .Why does the number of buckets matter?
1480 ********************************************************************************
1481 When looking up an item by its key, this hash scans linearly through the items
1482 in the appropriate bucket. In order for the linear scan to run in constant
1483 time, the number of items in each bucket must be bounded. This is accomplished
1484 by increasing the number of buckets as needed.
1485 ********************************************************************************
1489 This hash attempts to keep fewer than 10 items in each bucket. When an item is
1490 added that would cause a bucket to exceed this number, the number of buckets in
1491 the hash is doubled and the items are redistributed into the new buckets. In an
1492 ideal world, each bucket will then contain half as many items as it did before.
1494 Bucket expansion occurs automatically and invisibly as needed. There is
1495 no need for the application to know when it occurs.
1497 Per-bucket expansion threshold
1498 ++++++++++++++++++++++++++++++
1499 Normally all buckets share the same threshold (10 items) at which point bucket
1500 expansion is triggered. During the process of bucket expansion, uthash can
1501 adjust this expansion-trigger threshold on a per-bucket basis if it sees that
1502 certain buckets are over-utilized.
1504 When this threshold is adjusted, it goes from 10 to a multiple of 10 (for that
1505 particular bucket). The multiple is based on how many times greater the actual
1506 chain length is than the ideal length. It is a practical measure to reduce
1507 excess bucket expansion in the case where a hash function over-utilizes a few
1508 buckets but has good overall distribution. However, if the overall distribution
1509 gets too bad, uthash changes tactics.
1513 You usually don't need to know or worry about this, particularly if you used
1514 the `keystats` utility during development to select a good hash for your keys.
1516 A hash function may yield an uneven distribution of items across the buckets.
1517 In moderation this is not a problem. Normal bucket expansion takes place as
1518 the chain lengths grow. But when significant imbalance occurs (because the hash
1519 function is not well suited to the key domain), bucket expansion may be
1520 ineffective at reducing the chain lengths.
1522 Imagine a very bad hash function which always puts every item in bucket 0. No
1523 matter how many times the number of buckets is doubled, the chain length of
1524 bucket 0 stays the same. In a situation like this, the best behavior is to
1525 stop expanding, and accept 'O(n)' lookup performance. This is what uthash
1526 does. It degrades gracefully if the hash function is ill-suited to the keys.
1528 If two consecutive bucket expansions yield `ideal%` values below 50%, uthash
1529 inhibits expansion for that hash table. Once set, the 'bucket expansion
1530 inhibited' flag remains in effect as long as the hash has items in it.
1531 Inhibited expansion may cause `HASH_FIND` to exhibit worse than constant-time
1536 You don't need to use these hooks -- they are only here if you want to modify
1537 the behavior of uthash. Hooks can be used to replace standard library functions
1538 that might be unavailable on some platforms, to change how uthash allocates
1539 memory, or to run code in response to certain internal events.
1541 The `uthash.h` header will define these hooks to default values, unless they
1542 are already defined. It is safe either to `#undef` and redefine them
1543 after including `uthash.h`, or to define them before inclusion; for
1544 example, by passing `-Duthash_malloc=my_malloc` on the command line.
1546 Specifying alternate memory management functions
1547 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1548 By default this hash implementation uses `malloc` and `free` to manage memory.
1549 If your application uses its own custom allocator, this hash can use them too.
1551 ----------------------------------------------------------------------------
1554 /* undefine the defaults */
1555 #undef uthash_malloc
1558 /* re-define, specifying alternate functions */
1559 #define uthash_malloc(sz) my_malloc(sz)
1560 #define uthash_free(ptr,sz) my_free(ptr)
1563 ----------------------------------------------------------------------------
1565 Notice that `uthash_free` receives two parameters. The `sz` parameter is for
1566 convenience on embedded platforms that manage their own memory.
1568 Specifying alternate standard library functions
1569 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1570 Uthash also uses `strlen` (in the `HASH_FIND_STR` convenience macro, for
1571 example) and `memcmp` (as the method of comparing keys for equality). On
1572 platforms that do not provide these functions, you can substitute your own
1575 ----------------------------------------------------------------------------
1576 #undef uthash_memcmp
1577 #define uthash_memcmp(a,b,len) my_memcmp(a,b,len)
1579 #undef uthash_strlen
1580 #define uthash_strlen(s) my_strlen(s)
1581 ----------------------------------------------------------------------------
1585 If memory allocation fails (i.e., the malloc function returned `NULL`), the
1586 default behavior is to terminate the process by calling `exit(-1)`. This can
1587 be modified by re-defining the `uthash_fatal` macro.
1589 ----------------------------------------------------------------------------
1591 #define uthash_fatal(msg) my_fatal_function(msg)
1592 ----------------------------------------------------------------------------
1594 The fatal function should terminate the process or `longjmp` back to a safe
1595 place. Uthash does not support "returning a failure" if memory cannot be
1600 There is no need for the application to set these hooks or take action in
1601 response to these events. They are mainly for diagnostic purposes.
1603 These two hooks are "notification" hooks which get executed if uthash is
1604 expanding buckets, or setting the 'bucket expansion inhibited' flag. Normally
1605 both of these hooks are undefined and thus compile away to nothing.
1609 There is a hook for the bucket expansion event.
1611 ----------------------------------------------------------------------------
1612 #undef uthash_expand_fyi
1613 #define uthash_expand_fyi(tbl) printf("expanded to %d buckets\n", tbl->num_buckets)
1614 ----------------------------------------------------------------------------
1616 Expansion-inhibition
1617 ++++++++++++++++++++
1618 This hook can be defined to code to execute in the event that uthash decides to
1619 set the 'bucket expansion inhibited' flag.
1621 ----------------------------------------------------------------------------
1622 #undef uthash_noexpand_fyi
1623 #define uthash_noexpand_fyi printf("warning: bucket expansion inhibited\n")
1624 ----------------------------------------------------------------------------
1628 If a program that uses this hash is compiled with `-DHASH_DEBUG=1`, a special
1629 internal consistency-checking mode is activated. In this mode, the integrity
1630 of the whole hash is checked following every add or delete operation. This is
1631 for debugging the uthash software only, not for use in production code.
1633 In the `tests/` directory, running `make debug` will run all the tests in
1636 In this mode, any internal errors in the hash data structure will cause a
1637 message to be printed to `stderr` and the program to exit.
1639 The `UT_hash_handle` data structure includes `next`, `prev`, `hh_next` and
1640 `hh_prev` fields. The former two fields determine the "application" ordering
1641 (that is, insertion order-- the order the items were added). The latter two
1642 fields determine the "bucket chain" order. These link the `UT_hash_handles`
1643 together in a doubly-linked list that is a bucket chain.
1645 Checks performed in `-DHASH_DEBUG=1` mode:
1647 - the hash is walked in its entirety twice: once in 'bucket' order and a
1648 second time in 'application' order
1649 - the total number of items encountered in both walks is checked against the
1651 - during the walk in 'bucket' order, each item's `hh_prev` pointer is compared
1652 for equality with the last visited item
1653 - during the walk in 'application' order, each item's `prev` pointer is compared
1654 for equality with the last visited item
1657 ********************************************************************************
1658 Sometimes it's difficult to interpret a compiler warning on a line which
1659 contains a macro call. In the case of uthash, one macro can expand to dozens of
1660 lines. In this case, it is helpful to expand the macros and then recompile.
1661 By doing so, the warning message will refer to the exact line within the macro.
1663 Here is an example of how to expand the macros and then recompile. This uses the
1664 `test1.c` program in the `tests/` subdirectory.
1666 gcc -E -I../src test1.c > /tmp/a.c
1667 egrep -v '^#' /tmp/a.c > /tmp/b.c
1669 gcc -o /tmp/b /tmp/b.c
1671 The last line compiles the original program (test1.c) with all macros expanded.
1672 If there was a warning, the referenced line number can be checked in `/tmp/b.c`.
1673 ********************************************************************************
1677 You can use uthash in a threaded program. But you must do the locking. Use a
1678 read-write lock to protect against concurrent writes. It is ok to have
1679 concurrent readers (since uthash 1.5).
1681 For example using pthreads you can create an rwlock like this:
1683 pthread_rwlock_t lock;
1684 if (pthread_rwlock_init(&lock,NULL) != 0) fatal("can't create rwlock");
1686 Then, readers must acquire the read lock before doing any `HASH_FIND` calls or
1687 before iterating over the hash elements:
1689 if (pthread_rwlock_rdlock(&lock) != 0) fatal("can't get rdlock");
1690 HASH_FIND_INT(elts, &i, e);
1691 pthread_rwlock_unlock(&lock);
1693 Writers must acquire the exclusive write lock before doing any update. Add,
1694 delete, and sort are all updates that must be locked.
1696 if (pthread_rwlock_wrlock(&lock) != 0) fatal("can't get wrlock");
1698 pthread_rwlock_unlock(&lock);
1700 If you prefer, you can use a mutex instead of a read-write lock, but this will
1701 reduce reader concurrency to a single thread at a time.
1703 An example program using uthash with a read-write lock is included in
1704 `tests/threads/test1.c`.
1712 The convenience macros do the same thing as the generalized macros, but
1713 require fewer arguments.
1715 In order to use the convenience macros,
1717 1. the structure's `UT_hash_handle` field must be named `hh`, and
1718 2. for add or find, the key field must be of type `int` or `char[]` or pointer
1721 [width="90%",cols="10m,30m",grid="none",options="header"]
1722 |===============================================================================
1724 |HASH_ADD_INT | (head, keyfield_name, item_ptr)
1725 |HASH_REPLACE_INT | (head, keyfiled_name, item_ptr,replaced_item_ptr)
1726 |HASH_FIND_INT | (head, key_ptr, item_ptr)
1727 |HASH_ADD_STR | (head, keyfield_name, item_ptr)
1728 |HASH_REPLACE_STR | (head,keyfield_name, item_ptr, replaced_item_ptr)
1729 |HASH_FIND_STR | (head, key_ptr, item_ptr)
1730 |HASH_ADD_PTR | (head, keyfield_name, item_ptr)
1731 |HASH_REPLACE_PTR | (head, keyfield_name, item_ptr, replaced_item_ptr)
1732 |HASH_FIND_PTR | (head, key_ptr, item_ptr)
1733 |HASH_DEL | (head, item_ptr)
1734 |HASH_SORT | (head, cmp)
1735 |HASH_COUNT | (head)
1736 |===============================================================================
1741 These macros add, find, delete and sort the items in a hash. You need to
1742 use the general macros if your `UT_hash_handle` is named something other
1743 than `hh`, or if your key's data type isn't `int` or `char[]`.
1746 [width="90%",cols="10m,30m",grid="none",options="header"]
1747 |===============================================================================
1749 |HASH_ADD | (hh_name, head, keyfield_name, key_len, item_ptr)
1750 |HASH_ADD_BYHASHVALUE | (hh_name, head, keyfield_name, key_len, key_hash, item_ptr)
1751 |HASH_ADD_KEYPTR | (hh_name, head, key_ptr, key_len, item_ptr)
1752 |HASH_ADD_KEYPTR_BYHASHVALUE | (hh_name, head, key_ptr, key_len, key_hash, item_ptr)
1753 |HASH_ADD_INORDER | (hh_name, head, keyfield_name, key_len, item_ptr, cmp)
1754 |HASH_ADD_BYHASHVALUE_INORDER | (hh_name, head, keyfield_name, key_len, key_hash, item_ptr, cmp)
1755 |HASH_ADD_KEYPTR_INORDER | (hh_name, head, key_ptr, key_len, item_ptr, cmp)
1756 |HASH_ADD_KEYPTR_BYHASHVALUE_INORDER | (hh_name, head, key_ptr, key_len, key_hash, item_ptr, cmp)
1757 |HASH_REPLACE | (hh_name, head, keyfield_name, key_len, item_ptr, replaced_item_ptr)
1758 |HASH_REPLACE_BYHASHVALUE | (hh_name, head, keyfield_name, key_len, key_hash, item_ptr, replaced_item_ptr)
1759 |HASH_REPLACE_INORDER | (hh_name, head, keyfield_name, key_len, item_ptr, replaced_item_ptr, cmp)
1760 |HASH_REPLACE_BYHASHVALUE_INORDER | (hh_name, head, keyfield_name, key_len, key_hash, item_ptr, replaced_item_ptr, cmp)
1761 |HASH_FIND | (hh_name, head, key_ptr, key_len, item_ptr)
1762 |HASH_FIND_BYHASHVALUE | (hh_name, head, key_ptr, key_len, key_hash, item_ptr)
1763 |HASH_DELETE | (hh_name, head, item_ptr)
1764 |HASH_VALUE | (key_ptr, key_len, key_hash)
1765 |HASH_SRT | (hh_name, head, cmp)
1766 |HASH_CNT | (hh_name, head)
1767 |HASH_CLEAR | (hh_name, head)
1768 |HASH_SELECT | (dst_hh_name, dst_head, src_hh_name, src_head, condition)
1769 |HASH_ITER | (hh_name, head, item_ptr, tmp_item_ptr)
1770 |HASH_OVERHEAD | (hh_name, head)
1771 |===============================================================================
1774 `HASH_ADD_KEYPTR` is used when the structure contains a pointer to the
1775 key, rather than the key itself.
1777 The `HASH_VALUE` and `..._BYHASHVALUE` macros are a performance mechanism mainly for the
1778 special case of having different structures, in different hash tables, having
1779 identical keys. It allows the hash value to be obtained once and then passed
1780 in to the `..._BYHASHVALUE` macros, saving the expense of re-computing the hash value.
1783 Argument descriptions
1784 ^^^^^^^^^^^^^^^^^^^^^
1786 name of the `UT_hash_handle` field in the structure. Conventionally called
1789 the structure pointer variable which acts as the "head" of the hash. So
1790 named because it initially points to the first item that is added to the hash.
1792 the name of the key field in the structure. (In the case of a multi-field
1793 key, this is the first field of the key). If you're new to macros, it
1794 might seem strange to pass the name of a field as a parameter. See
1797 the length of the key field in bytes. E.g. for an integer key, this is
1798 `sizeof(int)`, while for a string key it's `strlen(key)`. (For a
1799 multi-field key, see the notes in this guide on calculating key length).
1801 for `HASH_FIND`, this is a pointer to the key to look up in the hash
1802 (since it's a pointer, you can't directly pass a literal value here). For
1803 `HASH_ADD_KEYPTR`, this is the address of the key of the item being added.
1805 the hash value of the provided key. This is an input parameter for the
1806 `..._BYHASHVALUE` macros, and an output parameter for `HASH_VALUE`.
1807 Reusing a cached hash value can be a performance optimization if
1808 you're going to do repeated lookups for the same key.
1810 pointer to the structure being added, deleted, replaced, or looked up, or the current
1811 pointer during iteration. This is an input parameter for the `HASH_ADD`,
1812 `HASH_DELETE`, and `HASH_REPLACE` macros, and an output parameter for `HASH_FIND`
1813 and `HASH_ITER`. (When using `HASH_ITER` to iterate, `tmp_item_ptr`
1814 is another variable of the same type as `item_ptr`, used internally).
1816 used in `HASH_REPLACE` macros. This is an output parameter that is set to point
1817 to the replaced item (if no item is replaced it is set to NULL).
1819 pointer to comparison function which accepts two arguments (pointers to
1820 items to compare) and returns an int specifying whether the first item
1821 should sort before, equal to, or after the second item (like `strcmp`).
1823 a function or macro which accepts a single argument-- a void pointer to a
1824 structure, which needs to be cast to the appropriate structure type. The
1825 function or macro should return (or evaluate to) a non-zero value if the
1826 structure should be "selected" for addition to the destination hash.
1828 // vim: set tw=80 wm=2 syntax=asciidoc: