1
0
Fork 0
You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.2 KiB
C

/*
* grow.c: generic growing array implementation
*/
#include <syslog.h>
#include "grow.h"
#include "config.h"
struct grow *grow_init(bool dealloc) {
struct grow *g = malloc(sizeof(struct grow));
if (g == NULL) {
syslog(cfg_log_facility | LOG_ERR, "grow: Could not initialize growing array: %m");
return NULL;
}
g -> arr = NULL;
g -> elems = 0;
g -> alloc = 0;
g -> active_elems = 0;
g -> dealloc = dealloc;
return g;
}
bool grow_push (void *val, struct grow *g) {
if (g -> alloc <= g -> elems) {
uint64_t new_size = g -> alloc == 0? 1 : 2* (g -> alloc);
void **new_arr = realloc(g -> arr, new_size * sizeof(void *));
if (new_arr == NULL) {
syslog(cfg_log_facility | LOG_ERR, "grow: could not resize growinging array: %m");
return false;
} else {
g -> arr = new_arr;
g -> alloc = new_size;
}
}
g -> arr[g -> elems] = val;
g -> elems++;
g -> active_elems++;
return true;
}
void *grow_pop (struct grow *g) {
if (g -> elems == 0) {
return NULL;
} else {
g -> elems--;
g -> active_elems--;
return g -> arr[g -> elems + 1];
}
}
void grow_drop (struct grow *g) {
if (g -> dealloc == true) {
for(uint64_t i = 0; i < g -> elems; i++) {
free(g->arr[i]);
}
}
free(g -> arr);
free(g);
return;
}