Add generic dynamic array type
This commit is contained in:
parent
89e548eca8
commit
7769f5fd58
6 changed files with 94 additions and 79 deletions
50
kubo_dynarray.h
Normal file
50
kubo_dynarray.h
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
#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
|
||||
Loading…
Add table
Add a link
Reference in a new issue