Line data Source code
1 : #include <passgen/assert.h> 2 : #include <passgen/config.h> 3 : #include <passgen/container/array.h> 4 : #include <stdlib.h> 5 : #include <string.h> 6 : 7 : #define SIZE_INITIAL 4 8 : 9 6 : void passgen_array_realloc(passgen_array *array, size_t capacity) { 10 6 : array->data = realloc(array->data, capacity * sizeof(void *)); 11 6 : array->capacity = capacity; 12 6 : } 13 : 14 : // Initialize array. Optionally takes a capacity, if so, memory that is 15 : // sufficiently large to hold `capacity` items will be allocated. 16 10638 : void passgen_array_init(passgen_array *array, size_t capacity) { 17 10638 : memset(array, 0, sizeof(*array)); 18 : 19 10638 : if(capacity) { 20 5 : passgen_array_realloc(array, capacity); 21 : } 22 10638 : } 23 : 24 : // Push an item to the back of the array. 25 9 : void passgen_array_push(passgen_array *array, void *pointer) { 26 9 : if(!array->data) { 27 0 : passgen_array_realloc(array, SIZE_INITIAL); 28 : } 29 : 30 9 : if(array->items == array->capacity) { 31 0 : passgen_array_realloc(array, array->capacity * 2); 32 : } 33 : 34 9 : array->data[array->items] = pointer; 35 9 : array->items += 1; 36 9 : } 37 : 38 : // Retrieve an item from the array. 39 3 : void *passgen_array_get(passgen_array *array, size_t pos) { 40 : #ifdef PASSGEN_DEBUG 41 3 : passgen_assert(pos <= array->items); 42 : #endif 43 : 44 3 : return array->data[pos]; 45 : } 46 : 47 : // Frees an array. 48 5 : void passgen_array_free(passgen_array *array) { 49 5 : free(array->data); 50 5 : PASSGEN_CLEAR(array); 51 5 : } 52 : 53 : // Pops the last item off the array and returns it. 54 4 : void *passgen_array_pop(passgen_array *array) { 55 4 : if(!array->items) { 56 1 : return NULL; 57 : } 58 : 59 3 : array->items -= 1; 60 3 : return array->data[array->items]; 61 : }