codebased/include/common/array.h
2023-04-25 02:13:20 +02:00

68 lines
4.3 KiB
C

#ifndef COMMON_ARRAY_H
#define COMMON_ARRAY_H
#include "common/linked.h"
#include "common/maybe_unused.h"
#include <stddef.h>
#include <stdlib.h>
#define ARRAY(TYPE, STRUCT_NAME, FUNCTION_PREFIX) \
typedef struct { \
TYPE* data; \
size_t length, capacity; \
} STRUCT_NAME; \
\
MAYBE_UNUSED static inline void FUNCTION_PREFIX##_construct( \
STRUCT_NAME* array \
) \
{ \
*array = (STRUCT_NAME) { \
.data = NULL, \
.length = 0, \
.capacity = 0, \
}; \
} \
\
MAYBE_UNUSED static inline void FUNCTION_PREFIX##_destroy( \
STRUCT_NAME* array \
) \
{ \
if (array->data) \
free(array->data); \
} \
\
MAYBE_UNUSED static inline size_t FUNCTION_PREFIX##_length( \
const STRUCT_NAME* array \
) \
{ \
return array->length; \
} \
\
MAYBE_UNUSED static inline TYPE* FUNCTION_PREFIX##_get( \
const STRUCT_NAME* array, size_t index \
) \
{ \
if (index >= array->length) \
return NULL; \
else \
return &array->data[index]; \
} \
\
MAYBE_UNUSED 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