Use an object pool for stack nodes, to reduce allocations

Also, fix some leaks in the case where memory allocation failed during parsing
This commit is contained in:
Max Brunsfeld 2016-02-04 11:15:46 -08:00
parent a302ee822a
commit c96c4a08e6
8 changed files with 196 additions and 103 deletions

View file

@ -18,21 +18,29 @@ typedef struct {
size_t element_size;
} Vector;
static inline Vector vector_new(size_t element_size, size_t capacity) {
static inline Vector vector_new(size_t element_size) {
Vector result;
result.contents = NULL;
result.size = 0;
result.capacity = capacity;
result.capacity = 0;
result.element_size = element_size;
if (capacity > 0) {
result.contents = ts_calloc(capacity, element_size);
if (!result.contents)
result.element_size = 0;
}
return result;
}
static inline bool vector_grow(Vector *self, size_t capacity) {
void *new_contents;
if (self->contents)
new_contents = ts_realloc(self->contents, capacity * self->element_size);
else
new_contents = ts_calloc(capacity, self->element_size);
if (!new_contents)
return false;
self->capacity = capacity;
self->contents = new_contents;
return true;
}
static inline bool vector_valid(Vector *self) {
return self->element_size > 0;
}
@ -41,6 +49,8 @@ static inline void vector_delete(Vector *self) {
if (self->contents) {
ts_free(self->contents);
self->contents = NULL;
self->size = 0;
self->capacity = 0;
}
}
@ -54,6 +64,12 @@ static inline void *vector_back(Vector *self) {
return vector_get(self, self->size - 1);
}
static inline void *vector_pop(Vector *self) {
void *result = vector_back(self);
self->size--;
return result;
}
static inline void vector_clear(Vector *self) {
self->size = 0;
}