5 * tcon - routines for creating typesafe generic containers
7 * This code lets users create a structure with a typecanary; your API
8 * is then a set of macros which check the type canary before calling
9 * the generic routines.
12 * #include <ccan/tcon/tcon.h>
15 * // A simple container class. Can only contain one thing though!
19 * static inline void container_add_raw(struct container *c, void *p)
23 * static inline void *container_get_raw(struct container *c)
28 * // This lets the user define their container type; includes a
29 * // "type canary" to check types against.
30 * #define DEFINE_TYPED_CONTAINER_STRUCT(name, type) \
31 * struct name { struct container raw; TCON(type canary); }
33 * // These macros make sure the container type and pointer match.
34 * #define container_add(c, p) \
35 * container_add_raw(&tcon_check((c), canary, (p))->raw, (p))
36 * #define container_get(c) \
37 * tcon_cast((c), canary, container_get_raw(&(c)->raw))
39 * // Now, let's define two different containers.
40 * DEFINE_TYPED_CONTAINER_STRUCT(int_container, int *);
41 * DEFINE_TYPED_CONTAINER_STRUCT(string_container, char *);
43 * int main(int argc, char *argv[])
45 * struct int_container ic;
46 * struct string_container sc;
48 * // We would get a warning if we used the wrong types...
49 * container_add(&ic, &argc);
50 * container_add(&sc, argv[argc-1]);
52 * printf("Last arg is %s of %i arguments\n",
53 * container_get(&sc), *container_get(&ic) - 1);
56 * // Given "foo" outputs "Last arg is foo of 1 arguments"
57 * // Given "foo bar" outputs "Last arg is bar of 2 arguments"
59 * License: CC0 (Public domain)
61 * Author: Rusty Russell <rusty@rustcorp.com.au>
63 int main(int argc, char *argv[])
65 /* Expect exactly one argument */
69 if (strcmp(argv[1], "depends") == 0) {