Also wrap reallocarray into a type-safe macro

This commit is contained in:
Vftdan 2024-08-19 20:59:56 +02:00
parent 2d5dc40c19
commit 7e4e56d8e2
4 changed files with 7 additions and 6 deletions

5
defs.h
View File

@ -12,8 +12,9 @@
// So for structs it is usually actual downcast, but for unions it is an upcast
#define DOWNCAST(contype, basename, ptr) containerof(ptr, contype, as_##basename)
// Expects ptr to be of type srctype* or void*, returns (dsttype*)ptr
#define IMPLICIT_CAST(dsttype, srctype, ptr) (((union { typeof(srctype) *src; typeof(dsttype) *dst; }){.src = ptr}).dst)
#define T_ALLOC(count, T) ((T*)calloc(count, sizeof(T)))
#define IMPLICIT_CAST(dsttype, srctype, ptr) (((union { typeof(srctype) *src; typeof(dsttype) *dst; }){.src = (ptr)}).dst)
#define T_ALLOC(count, T) ((T*)calloc((count), sizeof(T)))
#define T_REALLOC(ptr, count, T) ((T*)reallocarray(IMPLICIT_CAST(void, T, ptr), (count), sizeof(T)))
#define MODULE_CONSTRUCTOR(name) __attribute__((constructor)) static void name(void)

View File

@ -21,7 +21,7 @@ event_predicate_list_extend(EventPredicateList * lst)
EventPredicate *new_values;
if (lst->values) {
new_values = reallocarray(lst->values, capacity, sizeof(EventPredicate));
new_values = T_REALLOC(lst->values, capacity, EventPredicate);
} else {
new_values = T_ALLOC(capacity, EventPredicate);
}

View File

@ -5,7 +5,7 @@ static void
graph_channel_list_resize(GraphChannelList * lst, size_t target)
{
if (target > lst->length) {
GraphChannel **new_elements = reallocarray(lst->elements, target, sizeof(GraphChannel*));
GraphChannel **new_elements = T_REALLOC(lst->elements, target, GraphChannel*);
if (!new_elements) {
return;
}

View File

@ -10,13 +10,13 @@ io_subscription_list_extend(IOSubscriptionList * lst)
size_t capacity = lst->capacity;
capacity = capacity + (capacity >> 1) + 1;
int * new_fds = reallocarray(lst->fds, capacity, sizeof(int));
int * new_fds = T_REALLOC(lst->fds, capacity, int);
if (!new_fds) {
return false;
}
lst->fds = new_fds;
IOHandling ** new_subscribers = reallocarray(lst->subscribers, capacity, sizeof(IOHandling*));
IOHandling ** new_subscribers = T_REALLOC(lst->subscribers, capacity, IOHandling*);
if (!new_subscribers) {
return false;
}