Research portable Memory game | Исследовать портируемую игру Память
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1904 lines
73KB

  1. uthash User Guide
  2. =================
  3. Troy D. Hanson, Arthur O'Dwyer
  4. v2.3.0, February 2021
  5. To download uthash, follow this link back to the
  6. https://github.com/troydhanson/uthash[GitHub project page].
  7. Back to my http://troydhanson.github.io/[other projects].
  8. A hash in C
  9. -----------
  10. This document is written for C programmers. Since you're reading this, chances
  11. are that you know a hash is used for looking up items using a key. In scripting
  12. languages, hashes or "dictionaries" are used all the time. In C, hashes don't
  13. exist in the language itself. This software provides a hash table for C
  14. structures.
  15. What can it do?
  16. ~~~~~~~~~~~~~~~~~
  17. This software supports these operations on items in a hash table:
  18. 1. add/replace
  19. 2. find
  20. 3. delete
  21. 4. count
  22. 5. iterate
  23. 6. sort
  24. Is it fast?
  25. ~~~~~~~~~~~
  26. Add, find and delete are normally constant-time operations. This is influenced
  27. by your key domain and the hash function.
  28. This hash aims to be minimalistic and efficient. It's around 1000 lines of C.
  29. It inlines automatically because it's implemented as macros. It's fast as long
  30. as the hash function is suited to your keys. You can use the default hash
  31. function, or easily compare performance and choose from among several other
  32. <<hash_functions,built-in hash functions>>.
  33. Is it a library?
  34. ~~~~~~~~~~~~~~~~
  35. No, it's just a single header file: `uthash.h`. All you need to do is copy
  36. the header file into your project, and:
  37. #include "uthash.h"
  38. Since uthash is a header file only, there is no library code to link against.
  39. C/C++ and platforms
  40. ~~~~~~~~~~~~~~~~~~~
  41. This software can be used in C and C++ programs. It has been tested on:
  42. * Linux
  43. * Windows using Visual Studio 2008 and 2010
  44. * Solaris
  45. * OpenBSD
  46. * FreeBSD
  47. * Android
  48. Test suite
  49. ^^^^^^^^^^
  50. To run the test suite, enter the `tests` directory. Then,
  51. * on Unix platforms, run `make`
  52. * on Windows, run the "do_tests_win32.cmd" batch file. (You may edit the
  53. batch file if your Visual Studio is installed in a non-standard location).
  54. BSD licensed
  55. ~~~~~~~~~~~~
  56. This software is made available under the
  57. link:license.html[revised BSD license].
  58. It is free and open source.
  59. Download uthash
  60. ~~~~~~~~~~~~~~~
  61. Follow the links on https://github.com/troydhanson/uthash to clone uthash or get a zip file.
  62. Getting help
  63. ~~~~~~~~~~~~
  64. Please use the https://groups.google.com/d/forum/uthash[uthash Google Group] to
  65. ask questions. You can email it at uthash@googlegroups.com.
  66. Contributing
  67. ~~~~~~~~~~~~
  68. You may submit pull requests through GitHub. However, the maintainers of uthash
  69. value keeping it unchanged, rather than adding bells and whistles.
  70. Extras included
  71. ~~~~~~~~~~~~~~~
  72. Three "extras" come with uthash. These provide lists, dynamic arrays and
  73. strings:
  74. * link:utlist.html[utlist.h] provides linked list macros for C structures.
  75. * link:utarray.html[utarray.h] implements dynamic arrays using macros.
  76. * link:utstring.html[utstring.h] implements a basic dynamic string.
  77. History
  78. ~~~~~~~
  79. I wrote uthash in 2004-2006 for my own purposes. Originally it was hosted on
  80. SourceForge. Uthash was downloaded around 30,000 times between 2006-2013 then
  81. transitioned to GitHub. It's been incorporated into commercial software,
  82. academic research, and into other open-source software. It has also been added
  83. to the native package repositories for a number of Unix-y distros.
  84. When uthash was written, there were fewer options for doing generic hash tables
  85. in C than exist today. There are faster hash tables, more memory-efficient hash
  86. tables, with very different API's today. But, like driving a minivan, uthash is
  87. convenient, and gets the job done for many purposes.
  88. As of July 2016, uthash is maintained by Arthur O'Dwyer.
  89. Your structure
  90. --------------
  91. In uthash, a hash table is comprised of structures. Each structure represents a
  92. key-value association. One or more of the structure fields constitute the key.
  93. The structure pointer itself is the value.
  94. .Defining a structure that can be hashed
  95. ----------------------------------------------------------------------
  96. #include "uthash.h"
  97. struct my_struct {
  98. int id; /* key */
  99. char name[10];
  100. UT_hash_handle hh; /* makes this structure hashable */
  101. };
  102. ----------------------------------------------------------------------
  103. Note that, in uthash, your structure will never be moved or copied into another
  104. location when you add it into a hash table. This means that you can keep other
  105. data structures that safely point to your structure-- regardless of whether you
  106. add or delete it from a hash table during your program's lifetime.
  107. The key
  108. ~~~~~~~
  109. There are no restrictions on the data type or name of the key field. The key
  110. can also comprise multiple contiguous fields, having any names and data types.
  111. .Any data type... really?
  112. *****************************************************************************
  113. Yes, your key and structure can have any data type. Unlike function calls with
  114. fixed prototypes, uthash consists of macros-- whose arguments are untyped-- and
  115. thus able to work with any type of structure or key.
  116. *****************************************************************************
  117. Unique keys
  118. ^^^^^^^^^^^
  119. As with any hash, every item must have a unique key. Your application must
  120. enforce key uniqueness. Before you add an item to the hash table, you must
  121. first know (if in doubt, check!) that the key is not already in use. You
  122. can check whether a key already exists in the hash table using `HASH_FIND`.
  123. The hash handle
  124. ~~~~~~~~~~~~~~~
  125. The `UT_hash_handle` field must be present in your structure. It is used for
  126. the internal bookkeeping that makes the hash work. It does not require
  127. initialization. It can be named anything, but you can simplify matters by
  128. naming it `hh`. This allows you to use the easier "convenience" macros to add,
  129. find and delete items.
  130. A word about memory
  131. ~~~~~~~~~~~~~~~~~~~
  132. Overhead
  133. ^^^^^^^^
  134. The hash handle consumes about 32 bytes per item on a 32-bit system, or 56 bytes
  135. per item on a 64-bit system. The other overhead costs-- the buckets and the
  136. table-- are negligible in comparison. You can use `HASH_OVERHEAD` to get the
  137. overhead size, in bytes, for a hash table. See <<Macro_reference,Macro
  138. Reference>>.
  139. How clean up occurs
  140. ^^^^^^^^^^^^^^^^^^^
  141. Some have asked how uthash cleans up its internal memory. The answer is simple:
  142. 'when you delete the final item' from a hash table, uthash releases all the
  143. internal memory associated with that hash table, and sets its pointer to NULL.
  144. Hash operations
  145. ---------------
  146. This section introduces the uthash macros by example. For a more succinct
  147. listing, see <<Macro_reference,Macro Reference>>.
  148. .Convenience vs. general macros:
  149. *****************************************************************************
  150. The uthash macros fall into two categories. The 'convenience' macros can be used
  151. with integer, pointer or string keys (and require that you chose the conventional
  152. name `hh` for the `UT_hash_handle` field). The convenience macros take fewer
  153. arguments than the general macros, making their usage a bit simpler for these
  154. common types of keys.
  155. The 'general' macros can be used for any types of keys, or for multi-field keys,
  156. or when the `UT_hash_handle` has been named something other than `hh`. These
  157. macros take more arguments and offer greater flexibility in return. But if the
  158. convenience macros suit your needs, use them-- your code will be more readable.
  159. *****************************************************************************
  160. Declare the hash
  161. ~~~~~~~~~~~~~~~~
  162. Your hash must be declared as a `NULL`-initialized pointer to your structure.
  163. struct my_struct *users = NULL; /* important! initialize to NULL */
  164. Add item
  165. ~~~~~~~~
  166. Allocate and initialize your structure as you see fit. The only aspect
  167. of this that matters to uthash is that your key must be initialized to
  168. a unique value. Then call `HASH_ADD`. (Here we use the convenience macro
  169. `HASH_ADD_INT`, which offers simplified usage for keys of type `int`).
  170. .Add an item to a hash
  171. ----------------------------------------------------------------------
  172. void add_user(int user_id, char *name) {
  173. struct my_struct *s;
  174. s = malloc(sizeof(struct my_struct));
  175. s->id = user_id;
  176. strcpy(s->name, name);
  177. HASH_ADD_INT(users, id, s); /* id: name of key field */
  178. }
  179. ----------------------------------------------------------------------
  180. The first parameter to `HASH_ADD_INT` is the hash table, and the
  181. second parameter is the 'name' of the key field. Here, this is `id`. The
  182. last parameter is a pointer to the structure being added.
  183. [[validc]]
  184. .Wait.. the field name is a parameter?
  185. *******************************************************************************
  186. If you find it strange that `id`, which is the 'name of a field' in the
  187. structure, can be passed as a parameter... welcome to the world of macros. Don't
  188. worry; the C preprocessor expands this to valid C code.
  189. *******************************************************************************
  190. Key must not be modified while in-use
  191. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  192. Once a structure has been added to the hash, do not change the value of its key.
  193. Instead, delete the item from the hash, change the key, and then re-add it.
  194. Checking uniqueness
  195. ^^^^^^^^^^^^^^^^^^^
  196. In the example above, we didn't check to see if `user_id` was already a key
  197. of some existing item in the hash. *If there's any chance that duplicate keys
  198. could be generated by your program, you must explicitly check the uniqueness*
  199. before adding the key to the hash. If the key is already in the hash, you can
  200. simply modify the existing structure in the hash rather than adding the item.
  201. 'It is an error to add two items with the same key to the hash table'.
  202. Let's rewrite the `add_user` function to check whether the id is in the hash.
  203. Only if the id is not present in the hash, do we create the item and add it.
  204. Otherwise we just modify the structure that already exists.
  205. void add_user(int user_id, char *name) {
  206. struct my_struct *s;
  207. HASH_FIND_INT(users, &user_id, s); /* id already in the hash? */
  208. if (s == NULL) {
  209. s = (struct my_struct *)malloc(sizeof *s);
  210. s->id = user_id;
  211. HASH_ADD_INT(users, id, s); /* id: name of key field */
  212. }
  213. strcpy(s->name, name);
  214. }
  215. Why doesn't uthash check key uniqueness for you? It saves the cost of a hash
  216. lookup for those programs which don't need it- for example, programs whose keys
  217. are generated by an incrementing, non-repeating counter.
  218. However, if replacement is a common operation, it is possible to use the
  219. `HASH_REPLACE` macro. This macro, before adding the item, will try to find an
  220. item with the same key and delete it first. It also returns a pointer to the
  221. replaced item, so the user has a chance to de-allocate its memory.
  222. Passing the hash pointer into functions
  223. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  224. In the example above `users` is a global variable, but what if the caller wanted
  225. to pass the hash pointer 'into' the `add_user` function? At first glance it would
  226. appear that you could simply pass `users` as an argument, but that won't work
  227. right.
  228. /* bad */
  229. void add_user(struct my_struct *users, int user_id, char *name) {
  230. ...
  231. HASH_ADD_INT(users, id, s);
  232. }
  233. You really need to pass 'a pointer' to the hash pointer:
  234. /* good */
  235. void add_user(struct my_struct **users, int user_id, char *name) { ...
  236. ...
  237. HASH_ADD_INT(*users, id, s);
  238. }
  239. Note that we dereferenced the pointer in the `HASH_ADD` also.
  240. The reason it's necessary to deal with a pointer to the hash pointer is simple:
  241. the hash macros modify it (in other words, they modify the 'pointer itself' not
  242. just what it points to).
  243. Replace item
  244. ~~~~~~~~~~~~
  245. `HASH_REPLACE` macros are equivalent to HASH_ADD macros except they attempt
  246. to find and delete the item first. If it finds and deletes an item, it will
  247. also return that items pointer as an output parameter.
  248. Find item
  249. ~~~~~~~~~
  250. To look up a structure in a hash, you need its key. Then call `HASH_FIND`.
  251. (Here we use the convenience macro `HASH_FIND_INT` for keys of type `int`).
  252. .Find a structure using its key
  253. ----------------------------------------------------------------------
  254. struct my_struct *find_user(int user_id) {
  255. struct my_struct *s;
  256. HASH_FIND_INT(users, &user_id, s); /* s: output pointer */
  257. return s;
  258. }
  259. ----------------------------------------------------------------------
  260. Here, the hash table is `users`, and `&user_id` points to the key (an integer
  261. in this case). Last, `s` is the 'output' variable of `HASH_FIND_INT`. The
  262. final result is that `s` points to the structure with the given key, or
  263. is `NULL` if the key wasn't found in the hash.
  264. [NOTE]
  265. The middle argument is a 'pointer' to the key. You can't pass a literal key
  266. value to `HASH_FIND`. Instead assign the literal value to a variable, and pass
  267. a pointer to the variable.
  268. Delete item
  269. ~~~~~~~~~~~
  270. To delete a structure from a hash, you must have a pointer to it. (If you only
  271. have the key, first do a `HASH_FIND` to get the structure pointer).
  272. .Delete an item from a hash
  273. ----------------------------------------------------------------------
  274. void delete_user(struct my_struct *user) {
  275. HASH_DEL(users, user); /* user: pointer to deletee */
  276. free(user); /* optional; it's up to you! */
  277. }
  278. ----------------------------------------------------------------------
  279. Here again, `users` is the hash table, and `user` is a pointer to the
  280. structure we want to remove from the hash.
  281. uthash never frees your structure
  282. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  283. Deleting a structure just removes it from the hash table-- it doesn't `free`
  284. it. The choice of when to free your structure is entirely up to you; uthash
  285. will never free your structure. For example when using `HASH_REPLACE` macros,
  286. a replaced output argument is returned back, in order to make it possible for
  287. the user to de-allocate it.
  288. Delete can change the pointer
  289. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  290. The hash table pointer (which initially points to the first item added to the
  291. hash) can change in response to `HASH_DEL` (i.e. if you delete the first item
  292. in the hash table).
  293. Iterative deletion
  294. ^^^^^^^^^^^^^^^^^^
  295. The `HASH_ITER` macro is a deletion-safe iteration construct which expands
  296. to a simple 'for' loop.
  297. .Delete all items from a hash
  298. ----------------------------------------------------------------------
  299. void delete_all() {
  300. struct my_struct *current_user, *tmp;
  301. HASH_ITER(hh, users, current_user, tmp) {
  302. HASH_DEL(users, current_user); /* delete; users advances to next */
  303. free(current_user); /* optional- if you want to free */
  304. }
  305. }
  306. ----------------------------------------------------------------------
  307. All-at-once deletion
  308. ^^^^^^^^^^^^^^^^^^^^
  309. If you only want to delete all the items, but not free them or do any
  310. per-element clean up, you can do this more efficiently in a single operation:
  311. HASH_CLEAR(hh, users);
  312. Afterward, the list head (here, `users`) will be set to `NULL`.
  313. Count items
  314. ~~~~~~~~~~~
  315. The number of items in the hash table can be obtained using `HASH_COUNT`:
  316. .Count of items in the hash table
  317. ----------------------------------------------------------------------
  318. unsigned int num_users;
  319. num_users = HASH_COUNT(users);
  320. printf("there are %u users\n", num_users);
  321. ----------------------------------------------------------------------
  322. Incidentally, this works even if the list head (here, `users`) is `NULL`, in
  323. which case the count is 0.
  324. Iterating and sorting
  325. ~~~~~~~~~~~~~~~~~~~~~
  326. You can loop over the items in the hash by starting from the beginning and
  327. following the `hh.next` pointer.
  328. .Iterating over all the items in a hash
  329. ----------------------------------------------------------------------
  330. void print_users() {
  331. struct my_struct *s;
  332. for (s = users; s != NULL; s = s->hh.next) {
  333. printf("user id %d: name %s\n", s->id, s->name);
  334. }
  335. }
  336. ----------------------------------------------------------------------
  337. There is also an `hh.prev` pointer you could use to iterate backwards through
  338. the hash, starting from any known item.
  339. [[deletesafe]]
  340. Deletion-safe iteration
  341. ^^^^^^^^^^^^^^^^^^^^^^^
  342. In the example above, it would not be safe to delete and free `s` in the body
  343. of the 'for' loop, (because `s` is dereferenced each time the loop iterates).
  344. This is easy to rewrite correctly (by copying the `s->hh.next` pointer to a
  345. temporary variable 'before' freeing `s`), but it comes up often enough that a
  346. deletion-safe iteration macro, `HASH_ITER`, is included. It expands to a
  347. `for`-loop header. Here is how it could be used to rewrite the last example:
  348. struct my_struct *s, *tmp;
  349. HASH_ITER(hh, users, s, tmp) {
  350. printf("user id %d: name %s\n", s->id, s->name);
  351. /* ... it is safe to delete and free s here */
  352. }
  353. .A hash is also a doubly-linked list.
  354. *******************************************************************************
  355. Iterating backward and forward through the items in the hash is possible
  356. because of the `hh.prev` and `hh.next` fields. All the items in the hash can
  357. be reached by repeatedly following these pointers, thus the hash is also a
  358. doubly-linked list.
  359. *******************************************************************************
  360. If you're using uthash in a C++ program, you need an extra cast on the `for`
  361. iterator, e.g., `s = static_cast<my_struct*>(s->hh.next)`.
  362. Sorting
  363. ^^^^^^^
  364. The items in the hash are visited in "insertion order" when you follow the
  365. `hh.next` pointer. You can sort the items into a new order using `HASH_SORT`.
  366. HASH_SORT(users, name_sort);
  367. The second argument is a pointer to a comparison function. It must accept two
  368. pointer arguments (the items to compare), and must return an `int` which is
  369. less than zero, zero, or greater than zero, if the first item sorts before,
  370. equal to, or after the second item, respectively. (This is the same convention
  371. used by `strcmp` or `qsort` in the standard C library).
  372. int sort_function(void *a, void *b) {
  373. /* compare a to b (cast a and b appropriately)
  374. * return (int) -1 if (a < b)
  375. * return (int) 0 if (a == b)
  376. * return (int) 1 if (a > b)
  377. */
  378. }
  379. Below, `name_sort` and `id_sort` are two examples of sort functions.
  380. .Sorting the items in the hash
  381. ----------------------------------------------------------------------
  382. int name_sort(struct my_struct *a, struct my_struct *b) {
  383. return strcmp(a->name, b->name);
  384. }
  385. int id_sort(struct my_struct *a, struct my_struct *b) {
  386. return (a->id - b->id);
  387. }
  388. void sort_by_name() {
  389. HASH_SORT(users, name_sort);
  390. }
  391. void sort_by_id() {
  392. HASH_SORT(users, id_sort);
  393. }
  394. ----------------------------------------------------------------------
  395. When the items in the hash are sorted, the first item may change position. In
  396. the example above, `users` may point to a different structure after calling
  397. `HASH_SORT`.
  398. A complete example
  399. ~~~~~~~~~~~~~~~~~~
  400. We'll repeat all the code and embellish it with a `main()` function to form a
  401. working example.
  402. If this code was placed in a file called `example.c` in the same directory as
  403. `uthash.h`, it could be compiled and run like this:
  404. cc -o example example.c
  405. ./example
  406. Follow the prompts to try the program.
  407. .A complete program
  408. ----------------------------------------------------------------------
  409. #include <stdio.h> /* gets */
  410. #include <stdlib.h> /* atoi, malloc */
  411. #include <string.h> /* strcpy */
  412. #include "uthash.h"
  413. struct my_struct {
  414. int id; /* key */
  415. char name[10];
  416. UT_hash_handle hh; /* makes this structure hashable */
  417. };
  418. struct my_struct *users = NULL;
  419. void add_user(int user_id, char *name) {
  420. struct my_struct *s;
  421. HASH_FIND_INT(users, &user_id, s); /* id already in the hash? */
  422. if (s == NULL) {
  423. s = (struct my_struct *)malloc(sizeof *s);
  424. s->id = user_id;
  425. HASH_ADD_INT(users, id, s); /* id: name of key field */
  426. }
  427. strcpy(s->name, name);
  428. }
  429. struct my_struct *find_user(int user_id) {
  430. struct my_struct *s;
  431. HASH_FIND_INT(users, &user_id, s); /* s: output pointer */
  432. return s;
  433. }
  434. void delete_user(struct my_struct *user) {
  435. HASH_DEL(users, user); /* user: pointer to deletee */
  436. free(user);
  437. }
  438. void delete_all() {
  439. struct my_struct *current_user, *tmp;
  440. HASH_ITER(hh, users, current_user, tmp) {
  441. HASH_DEL(users, current_user); /* delete it (users advances to next) */
  442. free(current_user); /* free it */
  443. }
  444. }
  445. void print_users() {
  446. struct my_struct *s;
  447. for (s = users; s != NULL; s = (struct my_struct*)(s->hh.next)) {
  448. printf("user id %d: name %s\n", s->id, s->name);
  449. }
  450. }
  451. int name_sort(struct my_struct *a, struct my_struct *b) {
  452. return strcmp(a->name, b->name);
  453. }
  454. int id_sort(struct my_struct *a, struct my_struct *b) {
  455. return (a->id - b->id);
  456. }
  457. void sort_by_name() {
  458. HASH_SORT(users, name_sort);
  459. }
  460. void sort_by_id() {
  461. HASH_SORT(users, id_sort);
  462. }
  463. int main(int argc, char *argv[]) {
  464. char in[10];
  465. int id = 1, running = 1;
  466. struct my_struct *s;
  467. unsigned num_users;
  468. while (running) {
  469. printf(" 1. add user\n");
  470. printf(" 2. add/rename user by id\n");
  471. printf(" 3. find user\n");
  472. printf(" 4. delete user\n");
  473. printf(" 5. delete all users\n");
  474. printf(" 6. sort items by name\n");
  475. printf(" 7. sort items by id\n");
  476. printf(" 8. print users\n");
  477. printf(" 9. count users\n");
  478. printf("10. quit\n");
  479. gets(in);
  480. switch(atoi(in)) {
  481. case 1:
  482. printf("name?\n");
  483. add_user(id++, gets(in));
  484. break;
  485. case 2:
  486. printf("id?\n");
  487. gets(in); id = atoi(in);
  488. printf("name?\n");
  489. add_user(id, gets(in));
  490. break;
  491. case 3:
  492. printf("id?\n");
  493. s = find_user(atoi(gets(in)));
  494. printf("user: %s\n", s ? s->name : "unknown");
  495. break;
  496. case 4:
  497. printf("id?\n");
  498. s = find_user(atoi(gets(in)));
  499. if (s) delete_user(s);
  500. else printf("id unknown\n");
  501. break;
  502. case 5:
  503. delete_all();
  504. break;
  505. case 6:
  506. sort_by_name();
  507. break;
  508. case 7:
  509. sort_by_id();
  510. break;
  511. case 8:
  512. print_users();
  513. break;
  514. case 9:
  515. num_users = HASH_COUNT(users);
  516. printf("there are %u users\n", num_users);
  517. break;
  518. case 10:
  519. running = 0;
  520. break;
  521. }
  522. }
  523. delete_all(); /* free any structures */
  524. return 0;
  525. }
  526. ----------------------------------------------------------------------
  527. This program is included in the distribution in `tests/example.c`. You can run
  528. `make example` in that directory to compile it easily.
  529. Standard key types
  530. ------------------
  531. This section goes into specifics of how to work with different kinds of keys.
  532. You can use nearly any type of key-- integers, strings, pointers, structures, etc.
  533. [NOTE]
  534. .A note about float
  535. ================================================================================
  536. You can use floating point keys. This comes with the same caveats as with any
  537. program that tests floating point equality. In other words, even the tiniest
  538. difference in two floating point numbers makes them distinct keys.
  539. ================================================================================
  540. Integer keys
  541. ~~~~~~~~~~~~
  542. The preceding examples demonstrated use of integer keys. To recap, use the
  543. convenience macros `HASH_ADD_INT` and `HASH_FIND_INT` for structures with
  544. integer keys. (The other operations such as `HASH_DELETE` and `HASH_SORT` are
  545. the same for all types of keys).
  546. String keys
  547. ~~~~~~~~~~~
  548. If your structure has a string key, the operations to use depend on whether your
  549. structure 'points to' the key (`char *`) or the string resides `within` the
  550. structure (`char a[10]`). *This distinction is important*. As we'll see below,
  551. you need to use `HASH_ADD_KEYPTR` when your structure 'points' to a key (that is,
  552. the key itself is 'outside' of the structure); in contrast, use `HASH_ADD_STR`
  553. for a string key that is contained *within* your structure.
  554. [NOTE]
  555. .char[ ] vs. char*
  556. ================================================================================
  557. The string is 'within' the structure in the first example below-- `name` is a
  558. `char[10]` field. In the second example, the key is 'outside' of the
  559. structure-- `name` is a `char *`. So the first example uses `HASH_ADD_STR` but
  560. the second example uses `HASH_ADD_KEYPTR`. For information on this macro, see
  561. the <<Macro_reference,Macro reference>>.
  562. ================================================================================
  563. String 'within' structure
  564. ^^^^^^^^^^^^^^^^^^^^^^^^^
  565. .A string-keyed hash (string within structure)
  566. ----------------------------------------------------------------------
  567. #include <string.h> /* strcpy */
  568. #include <stdlib.h> /* malloc */
  569. #include <stdio.h> /* printf */
  570. #include "uthash.h"
  571. struct my_struct {
  572. char name[10]; /* key (string is WITHIN the structure) */
  573. int id;
  574. UT_hash_handle hh; /* makes this structure hashable */
  575. };
  576. int main(int argc, char *argv[]) {
  577. const char *names[] = { "joe", "bob", "betty", NULL };
  578. struct my_struct *s, *tmp, *users = NULL;
  579. for (int i = 0; names[i]; ++i) {
  580. s = (struct my_struct *)malloc(sizeof *s);
  581. strcpy(s->name, names[i]);
  582. s->id = i;
  583. HASH_ADD_STR(users, name, s);
  584. }
  585. HASH_FIND_STR(users, "betty", s);
  586. if (s) printf("betty's id is %d\n", s->id);
  587. /* free the hash table contents */
  588. HASH_ITER(hh, users, s, tmp) {
  589. HASH_DEL(users, s);
  590. free(s);
  591. }
  592. return 0;
  593. }
  594. ----------------------------------------------------------------------
  595. This example is included in the distribution in `tests/test15.c`. It prints:
  596. betty's id is 2
  597. String 'pointer' in structure
  598. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  599. Now, here is the same example but using a `char *` key instead of `char [ ]`:
  600. .A string-keyed hash (structure points to string)
  601. ----------------------------------------------------------------------
  602. #include <string.h> /* strcpy */
  603. #include <stdlib.h> /* malloc */
  604. #include <stdio.h> /* printf */
  605. #include "uthash.h"
  606. struct my_struct {
  607. const char *name; /* key */
  608. int id;
  609. UT_hash_handle hh; /* makes this structure hashable */
  610. };
  611. int main(int argc, char *argv[]) {
  612. const char *names[] = { "joe", "bob", "betty", NULL };
  613. struct my_struct *s, *tmp, *users = NULL;
  614. for (int i = 0; names[i]; ++i) {
  615. s = (struct my_struct *)malloc(sizeof *s);
  616. s->name = names[i];
  617. s->id = i;
  618. HASH_ADD_KEYPTR(hh, users, s->name, strlen(s->name), s);
  619. }
  620. HASH_FIND_STR(users, "betty", s);
  621. if (s) printf("betty's id is %d\n", s->id);
  622. /* free the hash table contents */
  623. HASH_ITER(hh, users, s, tmp) {
  624. HASH_DEL(users, s);
  625. free(s);
  626. }
  627. return 0;
  628. }
  629. ----------------------------------------------------------------------
  630. This example is included in `tests/test40.c`.
  631. Pointer keys
  632. ~~~~~~~~~~~~
  633. Your key can be a pointer. To be very clear, this means the 'pointer itself'
  634. can be the key (in contrast, if the thing 'pointed to' is the key, this is a
  635. different use case handled by `HASH_ADD_KEYPTR`).
  636. Here is a simple example where a structure has a pointer member, called `key`.
  637. .A pointer key
  638. ----------------------------------------------------------------------
  639. #include <stdio.h>
  640. #include <stdlib.h>
  641. #include "uthash.h"
  642. typedef struct {
  643. void *key;
  644. int i;
  645. UT_hash_handle hh;
  646. } el_t;
  647. el_t *hash = NULL;
  648. char *someaddr = NULL;
  649. int main() {
  650. el_t *d;
  651. el_t *e = (el_t *)malloc(sizeof *e);
  652. if (!e) return -1;
  653. e->key = (void*)someaddr;
  654. e->i = 1;
  655. HASH_ADD_PTR(hash, key, e);
  656. HASH_FIND_PTR(hash, &someaddr, d);
  657. if (d) printf("found\n");
  658. /* release memory */
  659. HASH_DEL(hash, e);
  660. free(e);
  661. return 0;
  662. }
  663. ----------------------------------------------------------------------
  664. This example is included in `tests/test57.c`. Note that the end of the program
  665. deletes the element out of the hash, (and since no more elements remain in the
  666. hash), uthash releases its internal memory.
  667. Structure keys
  668. ~~~~~~~~~~~~~~
  669. Your key field can have any data type. To uthash, it is just a sequence of
  670. bytes. Therefore, even a nested structure can be used as a key. We'll use the
  671. general macros `HASH_ADD` and `HASH_FIND` to demonstrate.
  672. NOTE: Structures contain padding (wasted internal space used to fulfill
  673. alignment requirements for the members of the structure). These padding bytes
  674. 'must be zeroed' before adding an item to the hash or looking up an item.
  675. Therefore always zero the whole structure before setting the members of
  676. interest. The example below does this-- see the two calls to `memset`.
  677. .A key which is a structure
  678. ----------------------------------------------------------------------
  679. #include <stdlib.h>
  680. #include <stdio.h>
  681. #include "uthash.h"
  682. typedef struct {
  683. char a;
  684. int b;
  685. } record_key_t;
  686. typedef struct {
  687. record_key_t key;
  688. /* ... other data ... */
  689. UT_hash_handle hh;
  690. } record_t;
  691. int main(int argc, char *argv[]) {
  692. record_t l, *p, *r, *tmp, *records = NULL;
  693. r = (record_t *)malloc(sizeof *r);
  694. memset(r, 0, sizeof *r);
  695. r->key.a = 'a';
  696. r->key.b = 1;
  697. HASH_ADD(hh, records, key, sizeof(record_key_t), r);
  698. memset(&l, 0, sizeof(record_t));
  699. l.key.a = 'a';
  700. l.key.b = 1;
  701. HASH_FIND(hh, records, &l.key, sizeof(record_key_t), p);
  702. if (p) printf("found %c %d\n", p->key.a, p->key.b);
  703. HASH_ITER(hh, records, p, tmp) {
  704. HASH_DEL(records, p);
  705. free(p);
  706. }
  707. return 0;
  708. }
  709. ----------------------------------------------------------------------
  710. This usage is nearly the same as use of a compound key explained below.
  711. Note that the general macros require the name of the `UT_hash_handle` to be
  712. passed as the first argument (here, this is `hh`). The general macros are
  713. documented in <<Macro_reference,Macro Reference>>.
  714. Advanced Topics
  715. ---------------
  716. Compound keys
  717. ~~~~~~~~~~~~~
  718. Your key can even comprise multiple contiguous fields.
  719. .A multi-field key
  720. ----------------------------------------------------------------------
  721. #include <stdlib.h> /* malloc */
  722. #include <stddef.h> /* offsetof */
  723. #include <stdio.h> /* printf */
  724. #include <string.h> /* memset */
  725. #include "uthash.h"
  726. #define UTF32 1
  727. typedef struct {
  728. UT_hash_handle hh;
  729. int len;
  730. char encoding; /* these two fields */
  731. int text[]; /* comprise the key */
  732. } msg_t;
  733. typedef struct {
  734. char encoding;
  735. int text[];
  736. } lookup_key_t;
  737. int main(int argc, char *argv[]) {
  738. unsigned keylen;
  739. msg_t *msg, *tmp, *msgs = NULL;
  740. lookup_key_t *lookup_key;
  741. int beijing[] = {0x5317, 0x4eac}; /* UTF-32LE for 北京 */
  742. /* allocate and initialize our structure */
  743. msg = (msg_t *)malloc(sizeof(msg_t) + sizeof(beijing));
  744. memset(msg, 0, sizeof(msg_t)+sizeof(beijing)); /* zero fill */
  745. msg->len = sizeof(beijing);
  746. msg->encoding = UTF32;
  747. memcpy(msg->text, beijing, sizeof(beijing));
  748. /* calculate the key length including padding, using formula */
  749. keylen = offsetof(msg_t, text) /* offset of last key field */
  750. + sizeof(beijing) /* size of last key field */
  751. - offsetof(msg_t, encoding); /* offset of first key field */
  752. /* add our structure to the hash table */
  753. HASH_ADD(hh, msgs, encoding, keylen, msg);
  754. /* look it up to prove that it worked :-) */
  755. msg = NULL;
  756. lookup_key = (lookup_key_t *)malloc(sizeof(*lookup_key) + sizeof(beijing));
  757. memset(lookup_key, 0, sizeof(*lookup_key) + sizeof(beijing));
  758. lookup_key->encoding = UTF32;
  759. memcpy(lookup_key->text, beijing, sizeof(beijing));
  760. HASH_FIND(hh, msgs, &lookup_key->encoding, keylen, msg);
  761. if (msg) printf("found \n");
  762. free(lookup_key);
  763. HASH_ITER(hh, msgs, msg, tmp) {
  764. HASH_DEL(msgs, msg);
  765. free(msg);
  766. }
  767. return 0;
  768. }
  769. ----------------------------------------------------------------------
  770. This example is included in the distribution in `tests/test22.c`.
  771. If you use multi-field keys, recognize that the compiler pads adjacent fields
  772. (by inserting unused space between them) in order to fulfill the alignment
  773. requirement of each field. For example a structure containing a `char` followed
  774. by an `int` will normally have 3 "wasted" bytes of padding after the char, in
  775. order to make the `int` field start on a multiple-of-4 address (4 is the length
  776. of the int).
  777. [[multifield_note]]
  778. .Calculating the length of a multi-field key:
  779. *******************************************************************************
  780. To determine the key length when using a multi-field key, you must include any
  781. intervening structure padding the compiler adds for alignment purposes.
  782. An easy way to calculate the key length is to use the `offsetof` macro from
  783. `<stddef.h>`. The formula is:
  784. key length = offsetof(last_key_field)
  785. + sizeof(last_key_field)
  786. - offsetof(first_key_field)
  787. In the example above, the `keylen` variable is set using this formula.
  788. *******************************************************************************
  789. When dealing with a multi-field key, you must zero-fill your structure before
  790. `HASH_ADD`'ing it to a hash table, or using its fields in a `HASH_FIND` key.
  791. In the previous example, `memset` is used to initialize the structure by
  792. zero-filling it. This zeroes out any padding between the key fields. If we
  793. didn't zero-fill the structure, this padding would contain random values. The
  794. random values would lead to `HASH_FIND` failures; as two "identical" keys will
  795. appear to mismatch if there are any differences within their padding.
  796. Alternatively, you can customize the global <<hash_keycompare,key comparison function>>
  797. and <<hash_functions,key hashing function>> to ignore the padding in your key.
  798. See <<hash_keycompare,Specifying an alternate key comparison function>>.
  799. [[multilevel]]
  800. Multi-level hash tables
  801. ~~~~~~~~~~~~~~~~~~~~~~~
  802. A multi-level hash table arises when each element of a hash table contains its
  803. own secondary hash table. There can be any number of levels. In a scripting
  804. language you might see:
  805. $items{bob}{age}=37
  806. The C program below builds this example in uthash: the hash table is called
  807. `items`. It contains one element (`bob`) whose own hash table contains one
  808. element (`age`) with value 37. No special functions are necessary to build
  809. a multi-level hash table.
  810. While this example represents both levels (`bob` and `age`) using the same
  811. structure, it would also be fine to use two different structure definitions.
  812. It would also be fine if there were three or more levels instead of two.
  813. .Multi-level hash table
  814. ----------------------------------------------------------------------
  815. #include <stdio.h>
  816. #include <string.h>
  817. #include <stdlib.h>
  818. #include "uthash.h"
  819. /* hash of hashes */
  820. typedef struct item {
  821. char name[10];
  822. struct item *sub;
  823. int val;
  824. UT_hash_handle hh;
  825. } item_t;
  826. item_t *items = NULL;
  827. int main(int argc, char *argvp[]) {
  828. item_t *item1, *item2, *tmp1, *tmp2;
  829. /* make initial element */
  830. item_t *i = malloc(sizeof(*i));
  831. strcpy(i->name, "bob");
  832. i->sub = NULL;
  833. i->val = 0;
  834. HASH_ADD_STR(items, name, i);
  835. /* add a sub hash table off this element */
  836. item_t *s = malloc(sizeof(*s));
  837. strcpy(s->name, "age");
  838. s->sub = NULL;
  839. s->val = 37;
  840. HASH_ADD_STR(i->sub, name, s);
  841. /* iterate over hash elements */
  842. HASH_ITER(hh, items, item1, tmp1) {
  843. HASH_ITER(hh, item1->sub, item2, tmp2) {
  844. printf("$items{%s}{%s} = %d\n", item1->name, item2->name, item2->val);
  845. }
  846. }
  847. /* clean up both hash tables */
  848. HASH_ITER(hh, items, item1, tmp1) {
  849. HASH_ITER(hh, item1->sub, item2, tmp2) {
  850. HASH_DEL(item1->sub, item2);
  851. free(item2);
  852. }
  853. HASH_DEL(items, item1);
  854. free(item1);
  855. }
  856. return 0;
  857. }
  858. ----------------------------------------------------------------------
  859. The example above is included in `tests/test59.c`.
  860. [[multihash]]
  861. Items in several hash tables
  862. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  863. A structure can be added to more than one hash table. A few reasons you might do
  864. this include:
  865. - each hash table may use a different key;
  866. - each hash table may have its own sort order;
  867. - or you might simply use multiple hash tables for grouping purposes. E.g.,
  868. you could have users in an `admin_users` and a `users` hash table.
  869. Your structure needs to have a `UT_hash_handle` field for each hash table to
  870. which it might be added. You can name them anything. E.g.,
  871. UT_hash_handle hh1, hh2;
  872. Items with multiple keys
  873. ~~~~~~~~~~~~~~~~~~~~~~~~
  874. You might create a hash table keyed on an ID field, and another hash table keyed
  875. on username (if usernames are unique). You can add the same user structure to
  876. both hash tables (without duplication of the structure), allowing lookup of a
  877. user structure by their name or ID. The way to achieve this is to have a
  878. separate `UT_hash_handle` for each hash to which the structure may be added.
  879. .A structure with two different keys
  880. ----------------------------------------------------------------------
  881. struct my_struct {
  882. int id; /* first key */
  883. char username[10]; /* second key */
  884. UT_hash_handle hh1; /* handle for first hash table */
  885. UT_hash_handle hh2; /* handle for second hash table */
  886. };
  887. ----------------------------------------------------------------------
  888. In the example above, the structure can now be added to two separate hash
  889. tables. In one hash, `id` is its key, while in the other hash, `username` is
  890. its key. (There is no requirement that the two hashes have different key
  891. fields. They could both use the same key, such as `id`).
  892. Notice the structure has two hash handles (`hh1` and `hh2`). In the code
  893. below, notice that each hash handle is used exclusively with a particular hash
  894. table. (`hh1` is always used with the `users_by_id` hash, while `hh2` is
  895. always used with the `users_by_name` hash table).
  896. .Two keys on a structure
  897. ----------------------------------------------------------------------
  898. struct my_struct *users_by_id = NULL, *users_by_name = NULL, *s;
  899. int i;
  900. char *name;
  901. s = malloc(sizeof(struct my_struct));
  902. s->id = 1;
  903. strcpy(s->username, "thanson");
  904. /* add the structure to both hash tables */
  905. HASH_ADD(hh1, users_by_id, id, sizeof(int), s);
  906. HASH_ADD(hh2, users_by_name, username, strlen(s->username), s);
  907. /* find user by ID in the "users_by_id" hash table */
  908. i = 1;
  909. HASH_FIND(hh1, users_by_id, &i, sizeof(int), s);
  910. if (s) printf("found id %d: %s\n", i, s->username);
  911. /* find user by username in the "users_by_name" hash table */
  912. name = "thanson";
  913. HASH_FIND(hh2, users_by_name, name, strlen(name), s);
  914. if (s) printf("found user %s: %d\n", name, s->id);
  915. ----------------------------------------------------------------------
  916. Sorted insertion of new items
  917. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  918. If you would like to maintain a sorted hash you have two options. The first
  919. option is to use the HASH_SRT() macro, which will sort any unordered list in
  920. 'O(n log(n))'. This is the best strategy if you're just filling up a hash
  921. table with items in random order with a single final HASH_SRT() operation
  922. when all is done. Obviously, this won't do what you want if you need
  923. the list to be in an ordered state at times between insertion of
  924. items. You can use HASH_SRT() after every insertion operation, but that will
  925. yield a computational complexity of 'O(n^2 log n)'.
  926. The second route you can take is via the in-order add and replace macros.
  927. The `HASH_ADD_INORDER*` macros work just like their `HASH_ADD*` counterparts, but
  928. with an additional comparison-function argument:
  929. int name_sort(struct my_struct *a, struct my_struct *b) {
  930. return strcmp(a->name, b->name);
  931. }
  932. HASH_ADD_KEYPTR_INORDER(hh, items, &item->name, strlen(item->name), item, name_sort);
  933. New items are sorted at insertion time in 'O(n)', thus resulting in a
  934. total computational complexity of 'O(n^2)' for the creation of the hash
  935. table with all items.
  936. For in-order add to work, the list must be in an ordered state before
  937. insertion of the new item.
  938. Several sort orders
  939. ~~~~~~~~~~~~~~~~~~~
  940. It comes as no surprise that two hash tables can have different sort orders, but
  941. this fact can also be used advantageously to sort the 'same items' in several
  942. ways. This is based on the ability to store a structure in several hash tables.
  943. Extending the previous example, suppose we have many users. We have added each
  944. user structure to the `users_by_id` hash table and the `users_by_name` hash table.
  945. (To reiterate, this is done without the need to have two copies of each structure.)
  946. Now we can define two sort functions, then use `HASH_SRT`.
  947. int sort_by_id(struct my_struct *a, struct my_struct *b) {
  948. if (a->id == b->id) return 0;
  949. return (a->id < b->id) ? -1 : 1;
  950. }
  951. int sort_by_name(struct my_struct *a, struct my_struct *b) {
  952. return strcmp(a->username, b->username);
  953. }
  954. HASH_SRT(hh1, users_by_id, sort_by_id);
  955. HASH_SRT(hh2, users_by_name, sort_by_name);
  956. Now iterating over the items in `users_by_id` will traverse them in id-order
  957. while, naturally, iterating over `users_by_name` will traverse them in
  958. name-order. The items are fully forward-and-backward linked in each order.
  959. So even for one set of users, we might store them in two hash tables to provide
  960. easy iteration in two different sort orders.
  961. Bloom filter (faster misses)
  962. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  963. Programs that generate a fair miss rate (`HASH_FIND` that result in `NULL`) may
  964. benefit from the built-in Bloom filter support. This is disabled by default,
  965. because programs that generate only hits would incur a slight penalty from it.
  966. Also, programs that do deletes should not use the Bloom filter. While the
  967. program would operate correctly, deletes diminish the benefit of the filter.
  968. To enable the Bloom filter, simply compile with `-DHASH_BLOOM=n` like:
  969. -DHASH_BLOOM=27
  970. where the number can be any value up to 32 which determines the amount of memory
  971. used by the filter, as shown below. Using more memory makes the filter more
  972. accurate and has the potential to speed up your program by making misses bail
  973. out faster.
  974. .Bloom filter sizes for selected values of n
  975. [width="50%",cols="10m,30",grid="none",options="header"]
  976. |=====================================================================
  977. | n | Bloom filter size (per hash table)
  978. | 16 | 8 kilobytes
  979. | 20 | 128 kilobytes
  980. | 24 | 2 megabytes
  981. | 28 | 32 megabytes
  982. | 32 | 512 megabytes
  983. |=====================================================================
  984. Bloom filters are only a performance feature; they do not change the results of
  985. hash operations in any way. The only way to gauge whether or not a Bloom filter
  986. is right for your program is to test it. Reasonable values for the size of the
  987. Bloom filter are 16-32 bits.
  988. Select
  989. ~~~~~~
  990. An experimental 'select' operation is provided that inserts those items from a
  991. source hash that satisfy a given condition into a destination hash. This
  992. insertion is done with somewhat more efficiency than if this were using
  993. `HASH_ADD`, namely because the hash function is not recalculated for keys of the
  994. selected items. This operation does not remove any items from the source hash.
  995. Rather the selected items obtain dual presence in both hashes. The destination
  996. hash may already have items in it; the selected items are added to it. In order
  997. for a structure to be usable with `HASH_SELECT`, it must have two or more hash
  998. handles. (As described <<multihash,here>>, a structure can exist in many
  999. hash tables at the same time; it must have a separate hash handle for each one).
  1000. user_t *users = NULL; /* hash table of users */
  1001. user_t *admins = NULL; /* hash table of admins */
  1002. typedef struct {
  1003. int id;
  1004. UT_hash_handle hh; /* handle for users hash */
  1005. UT_hash_handle ah; /* handle for admins hash */
  1006. } user_t;
  1007. Now suppose we have added some users, and want to select just the administrator
  1008. users who have id's less than 1024.
  1009. #define is_admin(x) (((user_t*)x)->id < 1024)
  1010. HASH_SELECT(ah, admins, hh, users, is_admin);
  1011. The first two parameters are the 'destination' hash handle and hash table, the
  1012. second two parameters are the 'source' hash handle and hash table, and the last
  1013. parameter is the 'select condition'. Here we used a macro `is_admin(x)` but we
  1014. could just as well have used a function.
  1015. int is_admin(const void *userv) {
  1016. user_t *user = (const user_t*)userv;
  1017. return (user->id < 1024) ? 1 : 0;
  1018. }
  1019. If the select condition always evaluates to true, this operation is
  1020. essentially a 'merge' of the source hash into the destination hash.
  1021. `HASH_SELECT` adds items to the destination without removing them from
  1022. the source; the source hash table remains unchanged. The destination hash table
  1023. must not be the same as the source hash table.
  1024. An example of using `HASH_SELECT` is included in `tests/test36.c`.
  1025. [[hash_keycompare]]
  1026. Specifying an alternate key comparison function
  1027. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1028. When you call `HASH_FIND(hh, head, intfield, sizeof(int), out)`, uthash will
  1029. first call <<hash_functions,`HASH_FUNCTION`>>`(intfield, sizeof(int), hashvalue)` to
  1030. determine the bucket `b` in which to search, and then, for each element `elt`
  1031. of bucket `b`, uthash will evaluate
  1032. `elt->hh.hashv == hashvalue && elt.hh.keylen == sizeof(int) && HASH_KEYCMP(intfield, elt->hh.key, sizeof(int)) == 0`.
  1033. `HASH_KEYCMP` should return `0` to indicate that `elt` is a match and should be
  1034. returned, and any non-zero value to indicate that the search for a matching
  1035. element should continue.
  1036. By default, uthash defines `HASH_KEYCMP` as an alias for `memcmp`. On platforms
  1037. that do not provide `memcmp`, you can substitute your own implementation.
  1038. ----------------------------------------------------------------------------
  1039. #undef HASH_KEYCMP
  1040. #define HASH_KEYCMP(a,b,len) bcmp(a, b, len)
  1041. ----------------------------------------------------------------------------
  1042. Another reason to substitute your own key comparison function is if your "key" is not
  1043. trivially comparable. In this case you will also need to substitute your own `HASH_FUNCTION`.
  1044. ----------------------------------------------------------------------------
  1045. struct Key {
  1046. short s;
  1047. /* 2 bytes of padding */
  1048. float f;
  1049. };
  1050. /* do not compare the padding bytes; do not use memcmp on floats */
  1051. unsigned key_hash(struct Key *s) { return s + (unsigned)f; }
  1052. bool key_equal(struct Key *a, struct Key *b) { return a.s == b.s && a.f == b.f; }
  1053. #define HASH_FUNCTION(s,len,hashv) (hashv) = key_hash((struct Key *)s)
  1054. #define HASH_KEYCMP(a,b,len) (!key_equal((struct Key *)a, (struct Key *)b))
  1055. ----------------------------------------------------------------------------
  1056. Another reason to substitute your own key comparison function is to trade off
  1057. correctness for raw speed. During its linear search of a bucket, uthash always
  1058. compares the 32-bit `hashv` first, and calls `HASH_KEYCMP` only if the `hashv`
  1059. compares equal. This means that `HASH_KEYCMP` is called at least once per
  1060. successful find. Given a good hash function, we expect the `hashv` comparison to
  1061. produce a "false positive" equality only once in four billion times. Therefore,
  1062. we expect `HASH_KEYCMP` to produce `0` most of the time. If we expect many
  1063. successful finds, and our application doesn't mind the occasional false positive,
  1064. we might substitute a no-op comparison function:
  1065. ----------------------------------------------------------------------------
  1066. #undef HASH_KEYCMP
  1067. #define HASH_KEYCMP(a,b,len) 0 /* occasionally wrong, but very fast */
  1068. ----------------------------------------------------------------------------
  1069. Note: The global equality-comparison function `HASH_KEYCMP` has no relationship
  1070. at all to the lessthan-comparison function passed as a parameter to `HASH_ADD_INORDER`.
  1071. [[hash_functions]]
  1072. Built-in hash functions
  1073. ~~~~~~~~~~~~~~~~~~~~~~~
  1074. Internally, a hash function transforms a key into a bucket number. You don't
  1075. have to take any action to use the default hash function, currently Jenkins.
  1076. Some programs may benefit from using another of the built-in hash functions.
  1077. There is a simple analysis utility included with uthash to help you determine
  1078. if another hash function will give you better performance.
  1079. You can use a different hash function by compiling your program with
  1080. `-DHASH_FUNCTION=HASH_xyz` where `xyz` is one of the symbolic names listed
  1081. below. E.g.,
  1082. cc -DHASH_FUNCTION=HASH_BER -o program program.c
  1083. .Built-in hash functions
  1084. [width="50%",cols="^5m,20",grid="none",options="header"]
  1085. |===============================================================================
  1086. |Symbol | Name
  1087. |JEN | Jenkins (default)
  1088. |BER | Bernstein
  1089. |SAX | Shift-Add-Xor
  1090. |OAT | One-at-a-time
  1091. |FNV | Fowler/Noll/Vo
  1092. |SFH | Paul Hsieh
  1093. |===============================================================================
  1094. Which hash function is best?
  1095. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1096. You can easily determine the best hash function for your key domain. To do so,
  1097. you'll need to run your program once in a data-collection pass, and then run
  1098. the collected data through an included analysis utility.
  1099. First you must build the analysis utility. From the top-level directory,
  1100. cd tests/
  1101. make
  1102. We'll use `test14.c` to demonstrate the data-collection and analysis steps
  1103. (here using `sh` syntax to redirect file descriptor 3 to a file):
  1104. .Using keystats
  1105. --------------------------------------------------------------------------------
  1106. % cc -DHASH_EMIT_KEYS=3 -I../src -o test14 test14.c
  1107. % ./test14 3>test14.keys
  1108. % ./keystats test14.keys
  1109. fcn ideal% #items #buckets dup% fl add_usec find_usec del-all usec
  1110. --- ------ ---------- ---------- ----- -- ---------- ---------- ------------
  1111. SFH 91.6% 1219 256 0% ok 92 131 25
  1112. FNV 90.3% 1219 512 0% ok 107 97 31
  1113. SAX 88.7% 1219 512 0% ok 111 109 32
  1114. OAT 87.2% 1219 256 0% ok 99 138 26
  1115. JEN 86.7% 1219 256 0% ok 87 130 27
  1116. BER 86.2% 1219 256 0% ok 121 129 27
  1117. --------------------------------------------------------------------------------
  1118. [NOTE]
  1119. The number 3 in `-DHASH_EMIT_KEYS=3` is a file descriptor. Any file descriptor
  1120. that your program doesn't use for its own purposes can be used instead of 3.
  1121. The data-collection mode enabled by `-DHASH_EMIT_KEYS=x` should not be used in
  1122. production code.
  1123. Usually, you should just pick the first hash function that is listed. Here, this
  1124. is `SFH`. This is the function that provides the most even distribution for
  1125. your keys. If several have the same `ideal%`, then choose the fastest one
  1126. according to the `find_usec` column.
  1127. keystats column reference
  1128. ^^^^^^^^^^^^^^^^^^^^^^^^^
  1129. fcn::
  1130. symbolic name of hash function
  1131. ideal%::
  1132. The percentage of items in the hash table which can be looked up within an
  1133. ideal number of steps. (Further explained below).
  1134. #items::
  1135. the number of keys that were read in from the emitted key file
  1136. #buckets::
  1137. the number of buckets in the hash after all the keys were added
  1138. dup%::
  1139. the percent of duplicate keys encountered in the emitted key file.
  1140. Duplicates keys are filtered out to maintain key uniqueness. (Duplicates
  1141. are normal. For example, if the application adds an item to a hash,
  1142. deletes it, then re-adds it, the key is written twice to the emitted file.)
  1143. flags::
  1144. this is either `ok`, or `nx` (noexpand) if the expansion inhibited flag is
  1145. set, described in <<expansion,Expansion internals>>. It is not recommended
  1146. to use a hash function that has the `noexpand` flag set.
  1147. add_usec::
  1148. the clock time in microseconds required to add all the keys to a hash
  1149. find_usec::
  1150. the clock time in microseconds required to look up every key in the hash
  1151. del-all usec::
  1152. the clock time in microseconds required to delete every item in the hash
  1153. [[ideal]]
  1154. ideal%
  1155. ^^^^^^
  1156. .What is ideal%?
  1157. *****************************************************************************
  1158. The 'n' items in a hash are distributed into 'k' buckets. Ideally each bucket
  1159. would contain an equal share '(n/k)' of the items. In other words, the maximum
  1160. linear position of any item in a bucket chain would be 'n/k' if every bucket is
  1161. equally used. If some buckets are overused and others are underused, the
  1162. overused buckets will contain items whose linear position surpasses 'n/k'.
  1163. Such items are considered non-ideal.
  1164. As you might guess, `ideal%` is the percentage of ideal items in the hash. These
  1165. items have favorable linear positions in their bucket chains. As `ideal%`
  1166. approaches 100%, the hash table approaches constant-time lookup performance.
  1167. *****************************************************************************
  1168. [[hashscan]]
  1169. hashscan
  1170. ~~~~~~~~
  1171. NOTE: This utility is only available on Linux, and on FreeBSD (8.1 and up).
  1172. A utility called `hashscan` is included in the `tests/` directory. It
  1173. is built automatically when you run `make` in that directory. This tool
  1174. examines a running process and reports on the uthash tables that it finds in
  1175. that program's memory. It can also save the keys from each table in a format
  1176. that can be fed into `keystats`.
  1177. Here is an example of using `hashscan`. First ensure that it is built:
  1178. cd tests/
  1179. make
  1180. Since `hashscan` needs a running program to inspect, we'll start up a simple
  1181. program that makes a hash table and then sleeps as our test subject:
  1182. ./test_sleep &
  1183. pid: 9711
  1184. Now that we have a test program, let's run `hashscan` on it:
  1185. ./hashscan 9711
  1186. Address ideal items buckets mc fl bloom/sat fcn keys saved to
  1187. ------------------ ----- -------- -------- -- -- --------- --- -------------
  1188. 0x862e038 81% 10000 4096 11 ok 16 14% JEN
  1189. If we wanted to copy out all its keys for external analysis using `keystats`,
  1190. add the `-k` flag:
  1191. ./hashscan -k 9711
  1192. Address ideal items buckets mc fl bloom/sat fcn keys saved to
  1193. ------------------ ----- -------- -------- -- -- --------- --- -------------
  1194. 0x862e038 81% 10000 4096 11 ok 16 14% JEN /tmp/9711-0.key
  1195. Now we could run `./keystats /tmp/9711-0.key` to analyze which hash function
  1196. has the best characteristics on this set of keys.
  1197. hashscan column reference
  1198. ^^^^^^^^^^^^^^^^^^^^^^^^^
  1199. Address::
  1200. virtual address of the hash table
  1201. ideal::
  1202. The percentage of items in the table which can be looked up within an ideal
  1203. number of steps. See <<ideal>> in the `keystats` section.
  1204. items::
  1205. number of items in the hash table
  1206. buckets::
  1207. number of buckets in the hash table
  1208. mc::
  1209. the maximum chain length found in the hash table (uthash usually tries to
  1210. keep fewer than 10 items in each bucket, or in some cases a multiple of 10)
  1211. fl::
  1212. flags (either `ok`, or `NX` if the expansion-inhibited flag is set)
  1213. bloom/sat::
  1214. if the hash table uses a Bloom filter, this is the size (as a power of two)
  1215. of the filter (e.g. 16 means the filter is 2^16 bits in size). The second
  1216. number is the "saturation" of the bits expressed as a percentage. The lower
  1217. the percentage, the more potential benefit to identify cache misses quickly.
  1218. fcn::
  1219. symbolic name of hash function
  1220. keys saved to::
  1221. file to which keys were saved, if any
  1222. .How hashscan works
  1223. *****************************************************************************
  1224. When hashscan runs, it attaches itself to the target process, which suspends
  1225. the target process momentarily. During this brief suspension, it scans the
  1226. target's virtual memory for the signature of a uthash hash table. It then
  1227. checks if a valid hash table structure accompanies the signature and reports
  1228. what it finds. When it detaches, the target process resumes running normally.
  1229. The hashscan is performed "read-only"-- the target process is not modified.
  1230. Since hashscan is analyzing a momentary snapshot of a running process, it may
  1231. return different results from one run to another.
  1232. *****************************************************************************
  1233. [[expansion]]
  1234. Expansion internals
  1235. ~~~~~~~~~~~~~~~~~~~
  1236. Internally this hash manages the number of buckets, with the goal of having
  1237. enough buckets so that each one contains only a small number of items.
  1238. .Why does the number of buckets matter?
  1239. ********************************************************************************
  1240. When looking up an item by its key, this hash scans linearly through the items
  1241. in the appropriate bucket. In order for the linear scan to run in constant
  1242. time, the number of items in each bucket must be bounded. This is accomplished
  1243. by increasing the number of buckets as needed.
  1244. ********************************************************************************
  1245. Normal expansion
  1246. ^^^^^^^^^^^^^^^^
  1247. This hash attempts to keep fewer than 10 items in each bucket. When an item is
  1248. added that would cause a bucket to exceed this number, the number of buckets in
  1249. the hash is doubled and the items are redistributed into the new buckets. In an
  1250. ideal world, each bucket will then contain half as many items as it did before.
  1251. Bucket expansion occurs automatically and invisibly as needed. There is
  1252. no need for the application to know when it occurs.
  1253. Per-bucket expansion threshold
  1254. ++++++++++++++++++++++++++++++
  1255. Normally all buckets share the same threshold (10 items) at which point bucket
  1256. expansion is triggered. During the process of bucket expansion, uthash can
  1257. adjust this expansion-trigger threshold on a per-bucket basis if it sees that
  1258. certain buckets are over-utilized.
  1259. When this threshold is adjusted, it goes from 10 to a multiple of 10 (for that
  1260. particular bucket). The multiple is based on how many times greater the actual
  1261. chain length is than the ideal length. It is a practical measure to reduce
  1262. excess bucket expansion in the case where a hash function over-utilizes a few
  1263. buckets but has good overall distribution. However, if the overall distribution
  1264. gets too bad, uthash changes tactics.
  1265. Inhibited expansion
  1266. ^^^^^^^^^^^^^^^^^^^
  1267. You usually don't need to know or worry about this, particularly if you used
  1268. the `keystats` utility during development to select a good hash for your keys.
  1269. A hash function may yield an uneven distribution of items across the buckets.
  1270. In moderation this is not a problem. Normal bucket expansion takes place as
  1271. the chain lengths grow. But when significant imbalance occurs (because the hash
  1272. function is not well suited to the key domain), bucket expansion may be
  1273. ineffective at reducing the chain lengths.
  1274. Imagine a very bad hash function which always puts every item in bucket 0. No
  1275. matter how many times the number of buckets is doubled, the chain length of
  1276. bucket 0 stays the same. In a situation like this, the best behavior is to
  1277. stop expanding, and accept 'O(n)' lookup performance. This is what uthash
  1278. does. It degrades gracefully if the hash function is ill-suited to the keys.
  1279. If two consecutive bucket expansions yield `ideal%` values below 50%, uthash
  1280. inhibits expansion for that hash table. Once set, the 'bucket expansion
  1281. inhibited' flag remains in effect as long as the hash has items in it.
  1282. Inhibited expansion may cause `HASH_FIND` to exhibit worse than constant-time
  1283. performance.
  1284. Diagnostic hooks
  1285. ^^^^^^^^^^^^^^^^
  1286. There are two "notification" hooks which get executed if uthash is
  1287. expanding buckets, or setting the 'bucket expansion inhibited' flag.
  1288. There is no need for the application to set these hooks or take action in
  1289. response to these events. They are mainly for diagnostic purposes.
  1290. Normally both of these hooks are undefined and thus compile away to nothing.
  1291. The `uthash_expand_fyi` hook can be defined to execute code whenever
  1292. uthash performs a bucket expansion.
  1293. ----------------------------------------------------------------------------
  1294. #undef uthash_expand_fyi
  1295. #define uthash_expand_fyi(tbl) printf("expanded to %u buckets\n", tbl->num_buckets)
  1296. ----------------------------------------------------------------------------
  1297. The `uthash_noexpand_fyi` hook can be defined to execute code whenever
  1298. uthash sets the 'bucket expansion inhibited' flag.
  1299. ----------------------------------------------------------------------------
  1300. #undef uthash_noexpand_fyi
  1301. #define uthash_noexpand_fyi(tbl) printf("warning: bucket expansion inhibited\n")
  1302. ----------------------------------------------------------------------------
  1303. Hooks
  1304. ~~~~~
  1305. You don't need to use these hooks -- they are only here if you want to modify
  1306. the behavior of uthash. Hooks can be used to replace standard library functions
  1307. that might be unavailable on some platforms, to change how uthash allocates
  1308. memory, or to run code in response to certain internal events.
  1309. The `uthash.h` header will define these hooks to default values, unless they
  1310. are already defined. It is safe either to `#undef` and redefine them
  1311. after including `uthash.h`, or to define them before inclusion; for
  1312. example, by passing `-Duthash_malloc=my_malloc` on the command line.
  1313. Specifying alternate memory management functions
  1314. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1315. By default, uthash uses `malloc` and `free` to manage memory.
  1316. If your application uses its own custom allocator, uthash can use them too.
  1317. ----------------------------------------------------------------------------
  1318. #include "uthash.h"
  1319. /* undefine the defaults */
  1320. #undef uthash_malloc
  1321. #undef uthash_free
  1322. /* re-define, specifying alternate functions */
  1323. #define uthash_malloc(sz) my_malloc(sz)
  1324. #define uthash_free(ptr, sz) my_free(ptr)
  1325. ...
  1326. ----------------------------------------------------------------------------
  1327. Notice that `uthash_free` receives two parameters. The `sz` parameter is for
  1328. convenience on embedded platforms that manage their own memory.
  1329. Specifying alternate standard library functions
  1330. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1331. Uthash also uses `strlen` (in the `HASH_FIND_STR` convenience macro, for
  1332. example) and `memset` (used only for zeroing memory). On platforms that do not
  1333. provide these functions, you can substitute your own implementations.
  1334. ----------------------------------------------------------------------------
  1335. #undef uthash_bzero
  1336. #define uthash_bzero(a, len) my_bzero(a, len)
  1337. #undef uthash_strlen
  1338. #define uthash_strlen(s) my_strlen(s)
  1339. ----------------------------------------------------------------------------
  1340. Out of memory
  1341. ^^^^^^^^^^^^^
  1342. If memory allocation fails (i.e., the `uthash_malloc` function returns `NULL`),
  1343. the default behavior is to terminate the process by calling `exit(-1)`. This
  1344. can be modified by re-defining the `uthash_fatal` macro.
  1345. ----------------------------------------------------------------------------
  1346. #undef uthash_fatal
  1347. #define uthash_fatal(msg) my_fatal_function(msg)
  1348. ----------------------------------------------------------------------------
  1349. The fatal function should terminate the process or `longjmp` back to a safe
  1350. place. Note that an allocation failure may leave allocated memory that cannot
  1351. be recovered. After `uthash_fatal`, the hash table object should be considered
  1352. unusable; it might not be safe even to run `HASH_CLEAR` on the hash table
  1353. when it is in this state.
  1354. To enable "returning a failure" if memory cannot be allocated, define the
  1355. macro `HASH_NONFATAL_OOM` before including the `uthash.h` header file. In this
  1356. case, `uthash_fatal` is not used; instead, each allocation failure results in
  1357. a single call to `uthash_nonfatal_oom(elt)` where `elt` is the address of the
  1358. element whose insertion triggered the failure. The default behavior of
  1359. `uthash_nonfatal_oom` is a no-op.
  1360. ----------------------------------------------------------------------------
  1361. #undef uthash_nonfatal_oom
  1362. #define uthash_nonfatal_oom(elt) perhaps_recover((element_t *) elt)
  1363. ----------------------------------------------------------------------------
  1364. Before the call to `uthash_nonfatal_oom`, the hash table is rolled back
  1365. to the state it was in prior to the problematic insertion; no memory is
  1366. leaked. It is safe to `throw` or `longjmp` out of the `uthash_nonfatal_oom`
  1367. handler.
  1368. The `elt` argument will be of the correct pointer-to-element type, unless
  1369. `uthash_nonfatal_oom` is invoked from `HASH_SELECT`, in which case it will
  1370. be of `void*` type and must be cast before using. In any case, `elt->hh.tbl`
  1371. will be `NULL`.
  1372. Allocation failure is possible only when adding elements to the hash table
  1373. (including the `ADD`, `REPLACE`, and `SELECT` operations).
  1374. `uthash_free` is not allowed to fail.
  1375. Debug mode
  1376. ~~~~~~~~~~
  1377. If a program that uses this hash is compiled with `-DHASH_DEBUG=1`, a special
  1378. internal consistency-checking mode is activated. In this mode, the integrity
  1379. of the whole hash is checked following every add or delete operation. This is
  1380. for debugging the uthash software only, not for use in production code.
  1381. In the `tests/` directory, running `make debug` will run all the tests in
  1382. this mode.
  1383. In this mode, any internal errors in the hash data structure will cause a
  1384. message to be printed to `stderr` and the program to exit.
  1385. The `UT_hash_handle` data structure includes `next`, `prev`, `hh_next` and
  1386. `hh_prev` fields. The former two fields determine the "application" ordering
  1387. (that is, insertion order-- the order the items were added). The latter two
  1388. fields determine the "bucket chain" order. These link the `UT_hash_handles`
  1389. together in a doubly-linked list that is a bucket chain.
  1390. Checks performed in `-DHASH_DEBUG=1` mode:
  1391. - the hash is walked in its entirety twice: once in 'bucket' order and a
  1392. second time in 'application' order
  1393. - the total number of items encountered in both walks is checked against the
  1394. stored number
  1395. - during the walk in 'bucket' order, each item's `hh_prev` pointer is compared
  1396. for equality with the last visited item
  1397. - during the walk in 'application' order, each item's `prev` pointer is compared
  1398. for equality with the last visited item
  1399. .Macro debugging:
  1400. ********************************************************************************
  1401. Sometimes it's difficult to interpret a compiler warning on a line which
  1402. contains a macro call. In the case of uthash, one macro can expand to dozens of
  1403. lines. In this case, it is helpful to expand the macros and then recompile.
  1404. By doing so, the warning message will refer to the exact line within the macro.
  1405. Here is an example of how to expand the macros and then recompile. This uses the
  1406. `test1.c` program in the `tests/` subdirectory.
  1407. gcc -E -I../src test1.c > /tmp/a.c
  1408. egrep -v '^#' /tmp/a.c > /tmp/b.c
  1409. indent /tmp/b.c
  1410. gcc -o /tmp/b /tmp/b.c
  1411. The last line compiles the original program (test1.c) with all macros expanded.
  1412. If there was a warning, the referenced line number can be checked in `/tmp/b.c`.
  1413. ********************************************************************************
  1414. Thread safety
  1415. ~~~~~~~~~~~~~
  1416. You can use uthash in a threaded program. But you must do the locking. Use a
  1417. read-write lock to protect against concurrent writes. It is ok to have
  1418. concurrent readers (since uthash 1.5).
  1419. For example using pthreads you can create an rwlock like this:
  1420. pthread_rwlock_t lock;
  1421. if (pthread_rwlock_init(&lock, NULL) != 0) fatal("can't create rwlock");
  1422. Then, readers must acquire the read lock before doing any `HASH_FIND` calls or
  1423. before iterating over the hash elements:
  1424. if (pthread_rwlock_rdlock(&lock) != 0) fatal("can't get rdlock");
  1425. HASH_FIND_INT(elts, &i, e);
  1426. pthread_rwlock_unlock(&lock);
  1427. Writers must acquire the exclusive write lock before doing any update. Add,
  1428. delete, and sort are all updates that must be locked.
  1429. if (pthread_rwlock_wrlock(&lock) != 0) fatal("can't get wrlock");
  1430. HASH_DEL(elts, e);
  1431. pthread_rwlock_unlock(&lock);
  1432. If you prefer, you can use a mutex instead of a read-write lock, but this will
  1433. reduce reader concurrency to a single thread at a time.
  1434. An example program using uthash with a read-write lock is included in
  1435. `tests/threads/test1.c`.
  1436. [[Macro_reference]]
  1437. Macro reference
  1438. ---------------
  1439. Convenience macros
  1440. ~~~~~~~~~~~~~~~~~~
  1441. The convenience macros do the same thing as the generalized macros, but
  1442. require fewer arguments.
  1443. In order to use the convenience macros,
  1444. 1. the structure's `UT_hash_handle` field must be named `hh`, and
  1445. 2. for add or find, the key field must be of type `int` or `char[]` or pointer
  1446. .Convenience macros
  1447. [width="90%",cols="10m,30m",grid="none",options="header"]
  1448. |===============================================================================
  1449. |macro | arguments
  1450. |HASH_ADD_INT | (head, keyfield_name, item_ptr)
  1451. |HASH_REPLACE_INT | (head, keyfield_name, item_ptr, replaced_item_ptr)
  1452. |HASH_FIND_INT | (head, key_ptr, item_ptr)
  1453. |HASH_ADD_STR | (head, keyfield_name, item_ptr)
  1454. |HASH_REPLACE_STR | (head, keyfield_name, item_ptr, replaced_item_ptr)
  1455. |HASH_FIND_STR | (head, key_ptr, item_ptr)
  1456. |HASH_ADD_PTR | (head, keyfield_name, item_ptr)
  1457. |HASH_REPLACE_PTR | (head, keyfield_name, item_ptr, replaced_item_ptr)
  1458. |HASH_FIND_PTR | (head, key_ptr, item_ptr)
  1459. |HASH_DEL | (head, item_ptr)
  1460. |HASH_SORT | (head, cmp)
  1461. |HASH_COUNT | (head)
  1462. |===============================================================================
  1463. General macros
  1464. ~~~~~~~~~~~~~~
  1465. These macros add, find, delete and sort the items in a hash. You need to
  1466. use the general macros if your `UT_hash_handle` is named something other
  1467. than `hh`, or if your key's data type isn't `int` or `char[]`.
  1468. .General macros
  1469. [width="90%",cols="10m,30m",grid="none",options="header"]
  1470. |===============================================================================
  1471. |macro | arguments
  1472. |HASH_ADD | (hh_name, head, keyfield_name, key_len, item_ptr)
  1473. |HASH_ADD_BYHASHVALUE | (hh_name, head, keyfield_name, key_len, hashv, item_ptr)
  1474. |HASH_ADD_KEYPTR | (hh_name, head, key_ptr, key_len, item_ptr)
  1475. |HASH_ADD_KEYPTR_BYHASHVALUE | (hh_name, head, key_ptr, key_len, hashv, item_ptr)
  1476. |HASH_ADD_INORDER | (hh_name, head, keyfield_name, key_len, item_ptr, cmp)
  1477. |HASH_ADD_BYHASHVALUE_INORDER | (hh_name, head, keyfield_name, key_len, hashv, item_ptr, cmp)
  1478. |HASH_ADD_KEYPTR_INORDER | (hh_name, head, key_ptr, key_len, item_ptr, cmp)
  1479. |HASH_ADD_KEYPTR_BYHASHVALUE_INORDER | (hh_name, head, key_ptr, key_len, hashv, item_ptr, cmp)
  1480. |HASH_REPLACE | (hh_name, head, keyfield_name, key_len, item_ptr, replaced_item_ptr)
  1481. |HASH_REPLACE_BYHASHVALUE | (hh_name, head, keyfield_name, key_len, hashv, item_ptr, replaced_item_ptr)
  1482. |HASH_REPLACE_INORDER | (hh_name, head, keyfield_name, key_len, item_ptr, replaced_item_ptr, cmp)
  1483. |HASH_REPLACE_BYHASHVALUE_INORDER | (hh_name, head, keyfield_name, key_len, hashv, item_ptr, replaced_item_ptr, cmp)
  1484. |HASH_FIND | (hh_name, head, key_ptr, key_len, item_ptr)
  1485. |HASH_FIND_BYHASHVALUE | (hh_name, head, key_ptr, key_len, hashv, item_ptr)
  1486. |HASH_DELETE | (hh_name, head, item_ptr)
  1487. |HASH_VALUE | (key_ptr, key_len, hashv)
  1488. |HASH_SRT | (hh_name, head, cmp)
  1489. |HASH_CNT | (hh_name, head)
  1490. |HASH_CLEAR | (hh_name, head)
  1491. |HASH_SELECT | (dst_hh_name, dst_head, src_hh_name, src_head, condition)
  1492. |HASH_ITER | (hh_name, head, item_ptr, tmp_item_ptr)
  1493. |HASH_OVERHEAD | (hh_name, head)
  1494. |===============================================================================
  1495. [NOTE]
  1496. `HASH_ADD_KEYPTR` is used when the structure contains a pointer to the
  1497. key, rather than the key itself.
  1498. The `HASH_VALUE` and `..._BYHASHVALUE` macros are a performance mechanism mainly for the
  1499. special case of having different structures, in different hash tables, having
  1500. identical keys. It allows the hash value to be obtained once and then passed
  1501. in to the `..._BYHASHVALUE` macros, saving the expense of re-computing the hash value.
  1502. Argument descriptions
  1503. ^^^^^^^^^^^^^^^^^^^^^
  1504. hh_name::
  1505. name of the `UT_hash_handle` field in the structure. Conventionally called
  1506. `hh`.
  1507. head::
  1508. the structure pointer variable which acts as the "head" of the hash. So
  1509. named because it initially points to the first item that is added to the hash.
  1510. keyfield_name::
  1511. the name of the key field in the structure. (In the case of a multi-field
  1512. key, this is the first field of the key). If you're new to macros, it
  1513. might seem strange to pass the name of a field as a parameter. See
  1514. <<validc,note>>.
  1515. key_len::
  1516. the length of the key field in bytes. E.g. for an integer key, this is
  1517. `sizeof(int)`, while for a string key it's `strlen(key)`. (For a
  1518. multi-field key, see <<multifield_note,this note>>.)
  1519. key_ptr::
  1520. for `HASH_FIND`, this is a pointer to the key to look up in the hash
  1521. (since it's a pointer, you can't directly pass a literal value here). For
  1522. `HASH_ADD_KEYPTR`, this is the address of the key of the item being added.
  1523. hashv::
  1524. the hash value of the provided key. This is an input parameter for the
  1525. `..._BYHASHVALUE` macros, and an output parameter for `HASH_VALUE`.
  1526. Reusing a cached hash value can be a performance optimization if
  1527. you're going to do repeated lookups for the same key.
  1528. item_ptr::
  1529. pointer to the structure being added, deleted, replaced, or looked up, or the current
  1530. pointer during iteration. This is an input parameter for the `HASH_ADD`,
  1531. `HASH_DELETE`, and `HASH_REPLACE` macros, and an output parameter for `HASH_FIND`
  1532. and `HASH_ITER`. (When using `HASH_ITER` to iterate, `tmp_item_ptr`
  1533. is another variable of the same type as `item_ptr`, used internally).
  1534. replaced_item_ptr::
  1535. used in `HASH_REPLACE` macros. This is an output parameter that is set to point
  1536. to the replaced item (if no item is replaced it is set to NULL).
  1537. cmp::
  1538. pointer to comparison function which accepts two arguments (pointers to
  1539. items to compare) and returns an int specifying whether the first item
  1540. should sort before, equal to, or after the second item (like `strcmp`).
  1541. condition::
  1542. a function or macro which accepts a single argument (a void pointer to a
  1543. structure, which needs to be cast to the appropriate structure type). The
  1544. function or macro should evaluate to a non-zero value if the
  1545. structure should be "selected" for addition to the destination hash.
  1546. // vim: set tw=80 wm=2 syntax=asciidoc: