5 * hashtable - hash table routines
7 * A hash table is an efficient structure for looking up keys. This version
8 * grows with usage and allows efficient deletion.
10 * Caveat: pointers placed into the hash must be aligned to 64 bits.
11 * ie. from malloc or because the structure they point to is aligned.
12 * An assert will be raised if this isn't true.
15 * #include <ccan/hashtable/hashtable.h>
16 * #include <ccan/hash/hash.h>
21 * struct name_to_digit {
26 * static struct name_to_digit map[] = {
39 * // Wrapper for rehash function pointer.
40 * static unsigned long rehash(const void *e, void *unused)
42 * return hash_string(((struct name_to_digit *)e)->name);
45 * // Comparison function.
46 * static bool streq(const void *e, void *string)
48 * return strcmp(((struct name_to_digit *)e)->name, string) == 0;
51 * // We let them add their own aliases, eg. --alias=v=5
52 * static void add_alias(struct hashtable *ht, const char *alias)
55 * struct name_to_digit *n;
57 * n = malloc(sizeof(*n));
58 * n->name = strdup(alias);
60 * eq = strchr(n->name, '=');
61 * if (!eq || ((n->val = atoi(eq+1)) == 0 && !strcmp(eq+1, "0")))
62 * errx(1, "Usage: --alias=<name>=<value>");
64 * hashtable_add(ht, hash_string(n->name), n);
67 * int main(int argc, char *argv[])
69 * struct hashtable *ht;
74 * errx(1, "Usage: %s [--alias=<name>=<val>]... <str>...",
77 * // Create and populate hash table.
78 * ht = hashtable_new(rehash, NULL);
79 * for (i = 0; i < sizeof(map)/sizeof(map[0]); i++)
80 * hashtable_add(ht, hash_string(map[i].name), &map[i]);
82 * // Add any aliases to the hash table.
83 * for (i = 1; i < argc; i++) {
84 * if (!strncmp(argv[i], "--alias=", strlen("--alias=")))
85 * add_alias(ht, argv[i] + strlen("--alias="));
90 * // Find the other args in the hash table.
91 * for (val = 0; i < argc; i++) {
92 * struct name_to_digit *n;
93 * n = hashtable_find(ht, hash_string(argv[i]),
96 * errx(1, "Invalid digit name %s", argv[i]);
97 * // Append it to the value we are building up.
101 * printf("%lu\n", val);
105 * License: GPLv2 (or later)
106 * Author: Rusty Russell <rusty@rustcorp.com.au>
108 int main(int argc, char *argv[])
113 if (strcmp(argv[1], "depends") == 0) {
114 printf("ccan/typesafe_cb\n");