4 * hashtable - hash table routines
6 * A hash table is an efficient structure for looking up keys. This version
7 * grows with usage and allows efficient deletion.
9 * Caveat: pointers placed into the hash must be aligned to 64 bits.
10 * ie. from malloc or because the structure they point to is aligned.
11 * An assert will be raised if this isn't true.
14 * #include <ccan/hashtable/hashtable.h>
15 * #include <ccan/hash/hash.h>
20 * struct name_to_digit {
25 * static struct name_to_digit map[] = {
38 * // Wrapper for rehash function pointer.
39 * static unsigned long rehash(const void *e, void *unused)
41 * return hash_string(((struct name_to_digit *)e)->name);
44 * // Comparison function.
45 * static bool streq(const void *e, void *string)
47 * return strcmp(((struct name_to_digit *)e)->name, string) == 0;
50 * // We let them add their own aliases, eg. --alias=v=5
51 * static void add_alias(struct hashtable *ht, const char *alias)
54 * struct name_to_digit *n;
56 * n = malloc(sizeof(*n));
57 * n->name = strdup(alias);
59 * eq = strchr(n->name, '=');
60 * if (!eq || ((n->val = atoi(eq+1)) == 0 && !strcmp(eq+1, "0")))
61 * errx(1, "Usage: --alias=<name>=<value>");
63 * hashtable_add(ht, hash_string(n->name), n);
66 * int main(int argc, char *argv[])
68 * struct hashtable *ht;
73 * errx(1, "Usage: %s [--alias=<name>=<val>]... <str>...",
76 * // Create and populate hash table.
77 * ht = hashtable_new(rehash, NULL);
78 * for (i = 0; i < sizeof(map)/sizeof(map[0]); i++)
79 * hashtable_add(ht, hash_string(map[i].name), &map[i]);
81 * // Add any aliases to the hash table.
82 * for (i = 1; i < argc; i++) {
83 * if (!strncmp(argv[i], "--alias=", strlen("--alias=")))
84 * add_alias(ht, argv[i] + strlen("--alias="));
89 * // Find the other args in the hash table.
90 * for (val = 0; i < argc; i++) {
91 * struct name_to_digit *n;
92 * n = hashtable_find(ht, hash_string(argv[i]),
95 * errx(1, "Invalid digit name %s", argv[i]);
96 * // Append it to the value we are building up.
100 * printf("%lu\n", val);
104 * Licence: GPLv2 (or later)
106 int main(int argc, char *argv[])
111 if (strcmp(argv[1], "depends") == 0) {