1 /* dynarr - dynamic resizable C array data structure
2 * author: John Tsiombikas <nuclear@member.fsf.org>
3 * license: public domain
10 * int *arr = dynarr_alloc(0, sizeof *arr);
13 * arr = dynarr_push(arr, &x);
15 * arr = dynarr_push(arr, &x);
17 * arr = dynarr_push(arr, &x);
19 * for(i=0; i<dynarr_size(arr); i++) {
20 * printf("%d\n", arr[i]);
25 void *dynarr_alloc(int elem, int szelem);
26 void dynarr_free(void *da);
27 void *dynarr_resize(void *da, int elem);
29 /* dynarr_empty returns non-zero if the array is empty
31 int dynarr_empty(void *da);
32 /* dynarr_size returns the number of elements in the array
34 int dynarr_size(void *da);
36 void *dynarr_clear(void *da);
39 void *dynarr_push(void *da, void *item);
40 void *dynarr_pop(void *da);
42 /* Finalize the array. No more resizing is possible after this call.
43 * Use free() instead of dynarr_free() to deallocate a finalized array.
44 * Returns pointer to the finalized array.
45 * dynarr_finalize can't fail.
48 void *dynarr_finalize(void *da);
51 #define DYNARR_RESIZE(da, n) \
52 do { (da) = dynarr_resize((da), (n)); } while(0)
53 #define DYNARR_CLEAR(da) \
54 do { (da) = dynarr_clear(da); } while(0)
55 #define DYNARR_PUSH(da, item) \
56 do { (da) = dynarr_push((da), (item)); } while(0)
57 #define DYNARR_POP(da) \
58 do { (da) = dynarr_pop(da); } while(0)
60 /* utility macros to push characters to a string. assumes and maintains
61 * the invariant that the last element is always a zero
63 #define DYNARR_STRPUSH(da, c) \
65 char cnull = 0, ch = (char)(c); \
66 (da) = dynarr_pop(da); \
67 (da) = dynarr_push((da), &ch); \
68 (da) = dynarr_push((da), &cnull); \
71 #define DYNARR_STRPOP(da) \
74 (da) = dynarr_pop(da); \
75 (da) = dynarr_pop(da); \
76 (da) = dynarr_push((da), &cnull); \
80 #endif /* DYNARR_H_ */