1 /* CC0 (Public domain) - see LICENSE file for details */
6 #include <ccan/str/str.h>
9 #define TAKE_LABEL(p) __FILE__ ":" stringify(__LINE__) ":" stringify(p)
11 #define TAKE_LABEL(p) NULL
15 * TAKES - annotate a formal parameter as being take()-able
17 * This doesn't do anything, but useful for documentation.
20 * void print_string(const char *str TAKES);
26 * take - record a pointer to be consumed by the function its handed to.
27 * @p: the pointer to mark, or NULL.
29 * This marks a pointer object to be freed by the called function,
30 * which is extremely useful for chaining functions. It works on
31 * NULL, for pass-through error handling.
33 #define take(p) (take_typeof(p) take_((p), TAKE_LABEL(p)))
36 * taken - check (and un-take) a pointer was passed with take()
37 * @p: the pointer to check.
39 * A function which accepts take() arguments uses this to see if it
40 * should own the pointer; it will be removed from the take list, so
41 * this only returns true once.
44 * // Silly routine to add 1
45 * static int *add_one(const int *num TAKES)
51 * ret = malloc(sizeof(int));
57 bool taken(const void *p);
60 * is_taken - check if a pointer was passed with take()
61 * @p: the pointer to check.
63 * This is like the above, but doesn't remove it from the taken list.
66 * // Silly routine to add 1: doesn't handle taken args!
67 * static int *add_one_notake(const int *num)
69 * int *ret = malloc(sizeof(int));
70 * assert(!is_taken(num));
76 bool is_taken(const void *p);
79 * taken_any - are there any taken pointers?
81 * Mainly useful for debugging take() leaks. With CCAN_TAKE_DEBUG, returns
82 * the label where the pointer was passed to take(), otherwise returns
83 * a static char buffer with the pointer value in it. NULL if none are taken.
86 * static void cleanup(void)
88 * assert(!taken_any());
91 const char *taken_any(void);
94 * take_cleanup - remove all taken pointers from list.
96 * This is useful in atexit() handlers for valgrind-style leak detection.
99 * static void cleanup2(void)
104 void take_cleanup(void);
107 * take_allocfail - set function to call if we can't reallocated taken array.
110 * If this is not set, then if the array reallocation fails, the
111 * pointer won't be marked taken(). If @fn returns, it is expected to
112 * free the pointer; we return NULL from take() and the function handles
113 * it like any allocation failure.
116 * static void free_on_fail(const void *p)
121 * static void init(void)
123 * take_allocfail(free_on_fail);
126 void take_allocfail(void (*fn)(const void *p));
128 /* Private functions */
130 #define take_typeof(ptr) (__typeof__(ptr))
132 #define take_typeof(ptr)
135 void *take_(const void *p, const char *label);
136 #endif /* CCAN_TAKE_H */