#include #include "mem.h" #include "vec.h" #define DEFAULT_LEN 8 void vec_init(struct vec *v, size_t unit_size) { v->data = NULL; v->len = 0; v->cap = 0; v->unit_size = unit_size; } void vec_push(struct vec *v, const void *item) { void *target; if (v->len == v->cap) { v->cap = (v->cap == 0) ? DEFAULT_LEN : v->cap * 2; v->data = REALLOC(v->data, v->cap * v->unit_size); } target = (char *)v->data + (v->len * v->unit_size); memcpy(target, item, v->unit_size); v->len++; } void *vec_pop(struct vec *v) { if (v->len == 0) return NULL; v->len--; return (char *)v->data + (v->len * v->unit_size); } void *vec_top(struct vec *v) { if (v->len == 0) return NULL; return (char *)v->data + ((v->len - 1) * v->unit_size); } void vec_free(struct vec *v) { free(v->data); v->data = NULL; v->len = v->cap = 0; }