77 lines
2 KiB
C
77 lines
2 KiB
C
#include <stdckdint.h>
|
|
#include <stddef.h>
|
|
#include <stdlib.h>
|
|
|
|
#include "error.h"
|
|
#include "vector.h"
|
|
|
|
static void grow_capacity(
|
|
struct type_erased_vector *vec,
|
|
size_t minimum_capacity,
|
|
char const function[static 1],
|
|
char const filename[static 1],
|
|
int linenum
|
|
) {
|
|
// 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(function, filename, linenum, "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(function, filename, linenum, "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,
|
|
char const function[static 1],
|
|
char const filename[static 1],
|
|
int linenum
|
|
) {
|
|
size_t new_size;
|
|
if (ckd_mul(&new_size, count, element_size)) {
|
|
panic_at(function, filename, linenum, "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, function, filename, linenum);
|
|
|
|
vec->size = new_size;
|
|
}
|
|
|
|
void vec_ensure_free_space(
|
|
struct type_erased_vector *vec,
|
|
size_t element_size,
|
|
char const function[static 1],
|
|
char const filename[static 1],
|
|
int linenum
|
|
) {
|
|
if (vec->capacity - vec->size >= element_size) {
|
|
return;
|
|
}
|
|
|
|
size_t minimum_capacity;
|
|
if (ckd_add(&minimum_capacity, vec->size, element_size)) {
|
|
panic_at(function, filename, linenum, "size_t overflow adding %zu to allocation size %zu", element_size, vec->size);
|
|
}
|
|
|
|
grow_capacity(vec, minimum_capacity, function, filename, linenum);
|
|
}
|