50 lines
3.2 KiB
C
50 lines
3.2 KiB
C
#ifndef KUBO_DYNARRAY_H
|
|
#define KUBO_DYNARRAY_H
|
|
|
|
#include <assert.h>
|
|
#include <stdlib.h>
|
|
|
|
#define KUBO_DRYNARRAY_DEFAULT_CAP 4
|
|
|
|
#define KUBO_DYNARRAY_REGISTER(name, type) \
|
|
struct name { \
|
|
type *data; \
|
|
size_t count; \
|
|
size_t capacity; \
|
|
}; \
|
|
\
|
|
static inline void name##_init(struct name *arr) { \
|
|
arr->count = 0; \
|
|
arr->capacity = KUBO_DRYNARRAY_DEFAULT_CAP; \
|
|
arr->data = malloc(sizeof(type) * arr->capacity); \
|
|
} \
|
|
\
|
|
static inline void name##_free(struct name *arr) { free(arr->data); } \
|
|
\
|
|
static inline bool name##_reserve(struct name *arr, size_t new_cap) { \
|
|
if (arr->capacity >= new_cap) \
|
|
return true; \
|
|
type *new_data = realloc(arr->data, sizeof(type) * new_cap); \
|
|
if (!new_data) \
|
|
return false; \
|
|
arr->data = new_data; \
|
|
arr->capacity = new_cap; \
|
|
return true; \
|
|
} \
|
|
\
|
|
static inline bool name##_add(struct name *arr, type new_val) { \
|
|
if (arr->count == arr->capacity - 1) { \
|
|
if (!name##_reserve(arr, arr->capacity * 2)) { \
|
|
return false; \
|
|
} \
|
|
} \
|
|
arr->data[arr->count++] = new_val; \
|
|
return true; \
|
|
} \
|
|
\
|
|
static inline type name##_get(struct name *arr, size_t index) { \
|
|
assert(index < arr->count); \
|
|
return arr->data[index]; \
|
|
}
|
|
|
|
#endif
|