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.
This commit is contained in:
Lennart Poettering
2021-05-19 16:42:19 +02:00
parent 6df28e1f84
commit 99480504d4
2 changed files with 47 additions and 0 deletions
+8
View File
@@ -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))