6 * tal/link - link helper for tal
8 * Tal does not support talloc-style references. In the cases where
9 * an object needs multiple parents, all parents need to be aware of
10 * the situation; thus tal/link is a helper where all "parents"
11 * tal_link an object they agree to share ownership of.
14 * // Silly program which keeps a cache of uppercased strings.
15 * // The cache wants to keep strings around even after they may have
16 * // been "freed" by the caller.
17 * // Given "hello" outputs "1 cache hits HELLO \n"
18 * // Given "hello hello there" outputs "4 cache hits HELLO HELLO THERE \n"
23 * #include <ccan/tal/link/link.h>
24 * #include <ccan/tal/str/str.h>
31 * static struct upcache *cache;
32 * static unsigned int cache_hits = 0;
33 * #define CACHE_SIZE 4
34 * static void init_upcase(void)
36 * cache = tal_arrz(NULL, struct upcache, CACHE_SIZE);
39 * static struct upcache *lookup_upcase(const char *str)
42 * for (i = 0; i < CACHE_SIZE; i++)
43 * if (cache[i].str && !strcmp(cache[i].str, str)) {
50 * static struct upcache *new_upcase(const char *str)
55 * upstr = tal_linkable(tal_strdup(NULL, str));
56 * i = random() % CACHE_SIZE;
58 * // Throw out old: works fine if cache[i].upstr is NULL.
59 * tal_delink(cache, cache[i].upstr);
61 * // Replace with new.
63 * cache[i].upstr = tal_link(cache, upstr);
65 * *upstr = toupper(*upstr);
71 * // If you want to keep the result, tal_link it.
72 * static const char *get_upcase(const char *str)
74 * struct upcache *uc = lookup_upcase(str);
76 * uc = new_upcase(str);
82 * static void exit_upcase(void)
85 * printf("%u cache hits ", cache_hits);
88 * int main(int argc, char *argv[])
91 * const char **values;
93 * // Initialize cache.
97 * values = tal_arr(NULL, const char *, argc);
98 * for (i = 1; i < argc; i++)
99 * values[i-1] = tal_link(values, get_upcase(argv[i]));
101 * // This will free all the values, but cache will still work.
105 * values = tal_arr(NULL, const char *, argc);
106 * for (i = 1; i < argc; i++)
107 * values[i-1] = tal_link(values, get_upcase(argv[i]));
109 * // This will remove cache links, but we still have a link.
112 * // Show values, so we output something.
113 * for (i = 0; i < argc - 1; i++)
114 * printf("%s ", values[i]);
117 * // This will finally free the upcase strings (last link).
124 * Author: Rusty Russell <rusty@rustcorp.com.au>
126 int main(int argc, char *argv[])
131 if (strcmp(argv[1], "depends") == 0) {
132 printf("ccan/container_of\n");
133 printf("ccan/list\n");
134 printf("ccan/tal\n");