60 lines
3.8 KiB
C
60 lines
3.8 KiB
C
#ifndef COMMON_GENERIC_ARRAY_H
|
|
#define COMMON_GENERIC_ARRAY_H
|
|
|
|
#include <stddef.h>
|
|
#include <stdlib.h>
|
|
|
|
#define GENERIC_ARRAY(Type, struct_name, function_prefix) \
|
|
typedef struct { \
|
|
Type* data; \
|
|
size_t length, capacity; \
|
|
} struct_name; \
|
|
\
|
|
static inline void function_prefix##_construct(struct_name* array) \
|
|
{ \
|
|
*array = (struct_name) { \
|
|
.data = NULL, \
|
|
.length = 0, \
|
|
.capacity = 0, \
|
|
}; \
|
|
} \
|
|
\
|
|
static inline void function_prefix##_destroy(struct_name* array) \
|
|
{ \
|
|
if (array->data) \
|
|
free(array->data); \
|
|
} \
|
|
\
|
|
static inline size_t function_prefix##_length(const struct_name* array) \
|
|
{ \
|
|
return array->length; \
|
|
} \
|
|
\
|
|
static inline Type* function_prefix##_get( \
|
|
const struct_name* array, size_t index \
|
|
) \
|
|
{ \
|
|
if (index >= array->length) \
|
|
return NULL; \
|
|
else \
|
|
return &array->data[index]; \
|
|
} \
|
|
\
|
|
static inline void function_prefix##_append( \
|
|
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
|