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