diff options
author | Luca Boccassi <bluca@debian.org> | 2023-09-23 19:29:32 +0200 |
---|---|---|
committer | Luca Boccassi <bluca@debian.org> | 2023-10-09 23:22:09 +0200 |
commit | 3b66a6764ec738392b075a306a60eaabf2a34f21 (patch) | |
tree | 1e56c54e22ac7922ed13503e15692565ebef78ef /src/fundamental/memory-util-fundamental.h | |
parent | efi: add xmemdup (diff) | |
download | systemd-3b66a6764ec738392b075a306a60eaabf2a34f21.tar.xz systemd-3b66a6764ec738392b075a306a60eaabf2a34f21.zip |
Move CLEANUP_ARRAY to src/fundamental
Diffstat (limited to 'src/fundamental/memory-util-fundamental.h')
-rw-r--r-- | src/fundamental/memory-util-fundamental.h | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/fundamental/memory-util-fundamental.h b/src/fundamental/memory-util-fundamental.h index 1ffacff21a..6870f54f58 100644 --- a/src/fundamental/memory-util-fundamental.h +++ b/src/fundamental/memory-util-fundamental.h @@ -70,3 +70,39 @@ static inline void erase_varp(struct VarEraser *e) { .p = (ptr), \ .size = (sz), \ } + +typedef void (*free_array_func_t)(void *p, size_t n); + +/* An automatic _cleanup_-like logic for destroy arrays (i.e. pointers + size) when leaving scope */ +typedef struct ArrayCleanup { + void **parray; + size_t *pn; + free_array_func_t pfunc; +} ArrayCleanup; + +static inline void array_cleanup(const ArrayCleanup *c) { + assert(c); + + assert(!c->parray == !c->pn); + + if (!c->parray) + return; + + if (*c->parray) { + assert(c->pfunc); + c->pfunc(*c->parray, *c->pn); + *c->parray = NULL; + } + + *c->pn = 0; +} + +#define CLEANUP_ARRAY(array, n, func) \ + _cleanup_(array_cleanup) _unused_ const ArrayCleanup CONCATENATE(_cleanup_array_, UNIQ) = { \ + .parray = (void**) &(array), \ + .pn = &(n), \ + .pfunc = (free_array_func_t) ({ \ + void (*_f)(typeof(array[0]) *a, size_t b) = func; \ + _f; \ + }), \ + } |