cusel/compiler/vector.c
2026-11-26 16:23:34 +02:00

102 lines
2.2 KiB
C

#include <stdckdint.h>
#include <stdlib.h>
#include <string.h>
#include "error.h"
#include "vector.h"
static void grow_capacity(
struct type_erased_vector *vec,
size_t minimum_capacity,
struct panic_location loc
) {
// Start off with a 1KiB minimum allocation size. (This is arbitrary
// and quite possibly a bad default.)
size_t new_capacity = 1024;
// Double the capacity until we can fit the target.
// TODO: There must be a better way to do this.
while (new_capacity < minimum_capacity) {
if (ckd_mul(&new_capacity, new_capacity, 2)) {
panic_at(
loc, "size_t overflow growing allocation to hold %zu bytes",
minimum_capacity
);
}
}
void *new_ptr = realloc(vec->ptr, new_capacity);
if (!new_ptr) {
panic_at_with_errno(
loc, "failed to resize a vector from %zu to %zu bytes",
vec->capacity, new_capacity
);
}
vec->capacity = new_capacity;
vec->ptr = new_ptr;
}
void vec_resize(
struct type_erased_vector *vec,
size_t count,
size_t element_size,
struct panic_location loc
) {
size_t new_size;
if (ckd_mul(&new_size, count, element_size)) {
panic_at(
loc, "size_t overflow multiplying element size %zu by count %zu",
element_size, count
);
}
// Fast path for when the backing allocation is large enough.
if (new_size <= vec->capacity) {
vec->size = new_size;
return;
}
grow_capacity(vec, new_size, loc);
vec->size = new_size;
}
void vec_free(struct type_erased_vector *vec) {
free(vec->ptr);
vec->ptr = NULL;
vec->size = 0;
vec->capacity = 0;
}
void vec_ensure_free_space(
struct type_erased_vector *vec,
size_t element_size,
struct panic_location loc
) {
if (vec->capacity - vec->size >= element_size) {
return;
}
size_t minimum_capacity;
if (ckd_add(&minimum_capacity, vec->size, element_size)) {
panic_at(
loc, "size_t overflow adding %zu to allocation size %zu",
element_size, vec->size
);
}
grow_capacity(vec, minimum_capacity, loc);
}
void vec_push(
struct type_erased_vector *vec,
void *element,
size_t element_size,
struct panic_location loc
) {
vec_ensure_free_space(vec, element_size, loc);
auto free_space = vec_free_space(*vec);
memcpy(free_space.ptr, element, element_size);
vec->size += element_size;
}