diff options
Diffstat (limited to 'dynarr.h')
-rw-r--r-- | dynarr.h | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/dynarr.h b/dynarr.h new file mode 100644 index 0000000..c86f146 --- /dev/null +++ b/dynarr.h @@ -0,0 +1,42 @@ +#ifndef DYNARR_H +#define DYNARR_H + +#include <stdlib.h> +#include <stdint.h> +#include <err.h> + +#define DYNARR(type) struct {\ + type *data;\ + size_t count;\ + size_t capacity;\ +}\ + +#define DA_INIT_CAP 16 +#define DA_INIT(da) {\ + (da)->count = 0;\ + (da)->capacity = DA_INIT_CAP;\ + (da)->data = malloc((da)->capacity * sizeof((da)->data[0]));\ +} + +#define DA_FIT(da, count)\ + if (count >= (da)->capacity) {\ + while (count >= (da)->capacity) (da)->capacity <<= 1;\ + (da)->data = realloc((da)->data, (da)->capacity * sizeof((da)->data[0]));\ + if (!(da)->data) err(1, "dynamic array reallocation failed");\ + } + +#define DA_FREE(da)\ + free((da)->data) + +#define DA_PUSH(da, item) {\ + DA_FIT(da, (da)->count + 1);\ + (da)->data[(da)->count++] = item;\ +} + +#define DA_FOR(da, type, name)\ + for (type *name = (da)->data; name < &(da)->data[(da)->count]; name++) + +#define DA_FORVAL(da, type, name)\ + for (type *da_iter = (da)->data, name; da_iter < &(da)->data[(da)->count] && (name = *da_iter); da_iter++) + +#endif |