diff options
author | Lennart Poettering <lennart@poettering.net> | 2021-05-18 22:30:10 +0200 |
---|---|---|
committer | Lennart Poettering <lennart@poettering.net> | 2021-05-19 16:42:19 +0200 |
commit | 99480504d47c0a6bbb1ac230cc33df12bbd36c54 (patch) | |
tree | 3efde30b90df8730e4798af13b5453f39343a170 /src/basic/alloc-util.h | |
parent | alloc-util: introduce MALLOC_SIZEOF_SAFE() helper (diff) | |
download | systemd-99480504d47c0a6bbb1ac230cc33df12bbd36c54.tar.xz systemd-99480504d47c0a6bbb1ac230cc33df12bbd36c54.zip |
alloc-util: add MALLOC_ELEMENTSOF() helper
This is a wrapper around malloc_usable_size() but is typesafe, and
divides by the element size.
A test it is also added ensuring what it does it does correcly.
Diffstat (limited to 'src/basic/alloc-util.h')
-rw-r--r-- | src/basic/alloc-util.h | 8 |
1 files changed, 8 insertions, 0 deletions
diff --git a/src/basic/alloc-util.h b/src/basic/alloc-util.h index 66bee6cb87..195795285b 100644 --- a/src/basic/alloc-util.h +++ b/src/basic/alloc-util.h @@ -175,3 +175,11 @@ void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size); * case. */ #define MALLOC_SIZEOF_SAFE(x) \ MIN(malloc_usable_size(x), __builtin_object_size(x, 0)) + +/* Inspired by ELEMENTSOF() but operates on malloc()'ed memory areas: typesafely returns the number of items + * that fit into the specified memory block */ +#define MALLOC_ELEMENTSOF(x) \ + (__builtin_choose_expr( \ + __builtin_types_compatible_p(typeof(x), typeof(&*(x))), \ + MALLOC_SIZEOF_SAFE(x)/sizeof((x)[0]), \ + VOID_0)) |