diff options
author | Leo Tenenbaum <pommicket@gmail.com> | 2019-08-28 21:21:28 -0400 |
---|---|---|
committer | Leo Tenenbaum <pommicket@gmail.com> | 2019-08-28 21:21:28 -0400 |
commit | e51b8fe8f43f6a1295367cd54c60c3c78b70ebb2 (patch) | |
tree | 3ef37ac9a5150fe4bf4dc39dcd321054be64fa01 /util | |
parent | 4227b244b99cdfb1a1022f7816e52256bcca4bc7 (diff) |
cleaned up code; work on types
Diffstat (limited to 'util')
-rw-r--r-- | util/arr.c | 22 | ||||
-rw-r--r-- | util/blockarr.c | 7 |
2 files changed, 15 insertions, 14 deletions
@@ -1,6 +1,5 @@ typedef struct { void *data; - void *last; size_t len; size_t cap; size_t item_sz; @@ -10,13 +9,19 @@ static void arr_create(Array *arr, size_t item_sz) { arr->len = arr->cap = 0; arr->item_sz = item_sz; arr->data = NULL; - arr->last = NULL; } static void arr_reserve(Array *arr, size_t n) { arr->cap = n; arr->data = realloc(arr->data, arr->item_sz * arr->cap); - arr->last = (void*)((char*)arr->data + arr->item_sz * (arr->len - 1)); + +} + +static void *arr_last(Array *arr) { + if (arr->data) + return (void*)((char*)arr->data + arr->item_sz * (arr->len - 1)); + else + return NULL; } static void *arr_add(Array *arr) { @@ -24,24 +29,19 @@ static void *arr_add(Array *arr) { arr_reserve(arr, (arr->cap + 1) * 2); } arr->len++; - arr->last = (char*)arr->last + arr->item_sz; - void *item = arr->last; - return item; + return (void*)((char*)arr->data + arr->item_sz * (arr->len - 1)); } static void arr_clear(Array *arr) { free(arr->data); arr->len = arr->cap = 0; arr->data = NULL; - arr->last = NULL; } static void arr_remove_last(Array *arr) { /* OPTIM (memory): Shorten array. */ arr->len--; - if (arr->len) { - arr->last = (char*)arr->last - arr->item_sz; - } else { + if (!arr->len) { arr_clear(arr); } @@ -51,4 +51,4 @@ static void arr_free(Array *arr) { free(arr->data); } -#define arr_foreach(arr, type, var) for (type *var = (arr)->data; var; var == (arr)->last ? var = NULL : var++) +#define arr_foreach(arr, type, var) for (type *var = (arr)->data, *var##_foreach_last = arr_last(arr); var; var == var##_foreach_last ? var = NULL : var++) diff --git a/util/blockarr.c b/util/blockarr.c index ea333df..c85df5a 100644 --- a/util/blockarr.c +++ b/util/blockarr.c @@ -28,8 +28,11 @@ void block_arr_create(BlockArr *arr, int lg_block_sz, size_t item_sz) { } void *block_arr_add(BlockArr *arr) { + ArrBlock *last_block; + last_block = arr_last(&arr->blocks); + if (arr->blocks.data == NULL || - (unsigned long)((ArrBlock*)arr->blocks.last)->n >= (1UL << arr->lg_block_sz)) { + (unsigned long)last_block->n >= (1UL << arr->lg_block_sz)) { ArrBlock *block; /* no blocks yet / ran out of blocks*/ block = arr_add(&arr->blocks); @@ -38,8 +41,6 @@ void *block_arr_add(BlockArr *arr) { block->last = block->data; return block->data; } else { - ArrBlock *last_block; - last_block = arr->blocks.last; last_block->last = (char*)last_block->last + arr->item_sz; return last_block->last; } |