diff options
| author | 2026-11-11 22:28:13 +0000 | |
|---|---|---|
| committer | 2026-11-11 22:47:34 +0000 | |
| commit | cb070b2d3f2b6e241e3be1b7e0eeb90fc755255f (patch) | |
| tree | c7d90c0abe9533c87d51b5196871846855efa1ba /src/da.h | |
| download | thesis-cb070b2d3f2b6e241e3be1b7e0eeb90fc755255f.tar.gz | |
Diffstat (limited to 'src/da.h')
| -rw-r--r-- | src/da.h | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/src/da.h b/src/da.h new file mode 100644 index 0000000..8eb0237 --- /dev/null +++ b/src/da.h | |||
| @@ -0,0 +1,68 @@ | |||
| 1 | // src/da.h --- Dynamic Array | ||
| 2 | #ifndef INCLUDED_DA_H | ||
| 3 | #define INCLUDED_DA_H | ||
| 4 | |||
| 5 | #ifndef DA_REALLOC | ||
| 6 | void *realloc (void *_ptr, size_t _size); | ||
| 7 | #define DA_REALLOC realloc | ||
| 8 | #endif | ||
| 9 | |||
| 10 | #ifndef DA_ASSERT | ||
| 11 | #include <assert.h> | ||
| 12 | #define DA_ASSERT assert | ||
| 13 | #endif | ||
| 14 | |||
| 15 | #ifndef DA_INIT_CAP | ||
| 16 | #define DA_INIT_CAP 256 | ||
| 17 | #endif | ||
| 18 | |||
| 19 | #define DA_ENSURE_CAPACITY(DA, COUNT) \ | ||
| 20 | ({ \ | ||
| 21 | if ((DA).count + (COUNT) > (DA).capacity) { \ | ||
| 22 | if ((DA).capacity == 0) \ | ||
| 23 | (DA).capacity = DA_INIT_CAP; \ | ||
| 24 | while ((DA).count + (COUNT) > (DA).capacity) \ | ||
| 25 | (DA).capacity *= 2; \ | ||
| 26 | (DA).items = DA_REALLOC ((DA).items, \ | ||
| 27 | (DA).capacity*sizeof (*(DA).items)); \ | ||
| 28 | DA_ASSERT((DA).items); \ | ||
| 29 | } \ | ||
| 30 | }) | ||
| 31 | |||
| 32 | #define DA_SHRINK(DA) \ | ||
| 33 | ({ \ | ||
| 34 | (DA).capacity = (DA).count; \ | ||
| 35 | (DA).items = REALLOC((DA).items, \ | ||
| 36 | (DA).capacity * \ | ||
| 37 | sizeof (*(DA).items)); \ | ||
| 38 | DA_ASSERT((DA).items); \ | ||
| 39 | }) | ||
| 40 | |||
| 41 | #define DA_APPEND(DA, ITEM) \ | ||
| 42 | ({ \ | ||
| 43 | DA_ENSURE_CAPACITY((DA), 1); \ | ||
| 44 | (DA).items[(DA).count++] = (ITEM); \ | ||
| 45 | }) | ||
| 46 | |||
| 47 | #define DA_APPEND_MANY(DA, NEW_ITEMS, NEW_ITEMS_COUNT) \ | ||
| 48 | ({ \ | ||
| 49 | DA_ENSURE_CAPACITY ((DA), (NEW_ITEMS_COUNT)); \ | ||
| 50 | memcpy ((DA).items + (DA).count, (NEW_ITEMS), \ | ||
| 51 | (NEW_ITEMS_COUNT)*sizeof (*(DA).items)); \ | ||
| 52 | (DA).count += (NEW_ITEMS_COUNT); \ | ||
| 53 | }) | ||
| 54 | |||
| 55 | #define DA_FIRST(DA) (DA).items[0] | ||
| 56 | #define DA_LAST(DA) (DA).items[(DA).count - 1] | ||
| 57 | |||
| 58 | #define DA_RESET(DA) ({ (DA).count = 0; }) | ||
| 59 | |||
| 60 | #define DA_FREE(DA) (void) DA_REALLOC ((DA).items, 0) | ||
| 61 | |||
| 62 | #define DA_FOR_EACH(ITEM, DA) for ( \ | ||
| 63 | typeof ((DA).items) ITEM = (DA).items; \ | ||
| 64 | ITEM < (DA).items + (DA).count; ++ITEM) | ||
| 65 | |||
| 66 | #endif // INCLUDED_DA_H | ||
| 67 | |||
| 68 | // src/da.h ends here | ||
