summary refs log tree commit diff
path: root/dynarr.h
blob: f8e5f200d0acdcdcb1ec67bcc31a4ddf7fa4752d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#ifndef DYNARR_H
#define DYNARR_H

#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <err.h>

#include "stdwrm.h"

typedef struct { size_t count, capacity; } DynArrHeader;

#define DYNARR(type) type *
#define DA_HEADER(da) ((DynArrHeader*)(da) - 1)

#define DA_INIT_CAP 16
#define DA_INIT(da) do {\
	char *da_init_ptr = ((char*)malloc(sizeof(DynArrHeader) + DA_INIT_CAP * sizeof(*da)));\
	if (!da_init_ptr) err(1, "dynamic array allocation failed");\
	da = (void *)(da_init_ptr + sizeof(DynArrHeader));\
	*DA_HEADER(da) = (DynArrHeader) { 0, DA_INIT_CAP };\
} while(0)

#define DA_FREE(da)\
	free(DA_HEADER(da))

#define DA_LEN(da) (DA_HEADER(da)->count)
#define DA_FIT(da, count) do {\
	if (count >= DA_HEADER(da)->capacity) {\
		while (count >= DA_HEADER(da)->capacity) DA_HEADER(da)->capacity <<= 1;\
		char *da_fit_ptr = realloc(DA_HEADER(da), sizeof(DynArrHeader) + DA_HEADER(da)->capacity * sizeof(*da));\
		if (!da_fit_ptr) err(1, "dynamic array reallocation failed");\
		(da) = (void *)(da_fit_ptr + sizeof(DynArrHeader));\
	}\
} while(0)

#define DA_PUSH(da, ...) do {\
	DA_FIT(da, DA_LEN(da) + 1);\
	(da)[DA_HEADER(da)->count++] = (__VA_ARGS__);\
} while(0)

#define DA_PUSH_MULT(da, buf, n) do {\
	DA_FIT(da, DA_LEN(da) + n);\
	memcpy(&(da)[DA_HEADER(da)->count], buf, n * sizeof(*(da)));\
	DA_HEADER(da)->count += n;\
} while(0)

#define DA_FOR(da, name)\
	for (typeof(da) name = (da); name < &(da)[DA_LEN(da)]; name++)

#define DA_FORVAL(da, name)\
	for (volatile typeof(*(da)) *da_iter = (da), name; da_iter < &(da)[DA_LEN(da)] && (name = *da_iter, 1); da_iter++)

#endif