codebased/include/utils/generic_array.h
2023-04-13 02:29:49 +02:00

62 lines
4.0 KiB
C

#ifndef UTILS_GENERIC_ARRAY_H
#define UTILS_GENERIC_ARRAY_H
#include <stddef.h>
#include <stdlib.h>
#define GENERIC_ARRAY(Type, struct_name, function_prefix) \
struct struct_name { \
Type* data; \
size_t length, capacity; \
}; \
\
static inline void function_prefix##_construct(struct struct_name* array) \
{ \
*array = (struct struct_name) { \
.data = NULL, \
.length = 0, \
.capacity = 0, \
}; \
} \
\
static inline void function_prefix##_destroy(struct struct_name* array) \
{ \
if (array->data) \
free(array->data); \
} \
\
static inline size_t function_prefix##_length( \
const struct struct_name* array \
) \
{ \
return array->length; \
} \
\
static inline Type* function_prefix##_get( \
const struct struct_name* array, size_t index \
) \
{ \
if (index >= array->length) \
return NULL; \
else \
return &array->data[index]; \
} \
\
static inline void function_prefix##_append( \
struct struct_name* array, Type value \
) \
{ \
if (array->data == NULL) { \
array->capacity = 8; \
array->data = malloc(sizeof(Type) * array->capacity); \
} else if (array->length == array->capacity) { \
array->capacity *= 2; \
array->data \
= realloc(array->data, sizeof(Type) * array->capacity); \
} \
array->data[array->length] = value; \
array->length++; \
}
#endif