cusel/compiler/vector.h
2026-11-18 23:41:26 +02:00

81 lines
1.7 KiB
C

struct type_erased_vector {
// Put the size_t fields first, so that dummy_pointer will alias
// them and more likely trigger a segfault if we accidentally use
// it.
size_t capacity;
size_t size;
void *ptr;
};
#define VEC(type) struct vec_##type { \
union { \
struct type_erased_vector data; \
type *dummy_pointer; \
}; \
}
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
);
#define VEC_RESIZE(vec, count) vec_resize( \
&(vec).data, \
(count), \
sizeof *(vec).dummy_pointer, \
__func__, \
__FILE__, \
__LINE__ \
);
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
);
#define VEC_ENSURE_FREE_SPACE(vec) vec_ensure_free_space( \
&(vec).data, \
sizeof *(vec).dummy_pointer, \
__func__, \
__FILE__, \
__LINE__ \
);
struct type_erased_span {
size_t size;
void *ptr;
};
#define SPAN(type) struct span_##type {\
union { \
struct type_erased_span data; \
type *dummy_pointer; \
}; \
}
static inline struct type_erased_span vec_free_space(
struct type_erased_vector vec
) {
// We can't do pointer arithmetic portably on void*, but char* has
// the correct semantics aiui universally.
char *ptr = vec.ptr;
return (struct type_erased_span) {
.ptr = ptr + vec.size,
.size = vec.capacity - vec.size,
};
}
#define VEC_FREE_SPACE(type, vec) _Generic((vec).dummy_pointer, \
type*: (SPAN(type)) { \
.data = vec_free_space((vec).data) \
} \
)
#define LENGTH(span_or_vec) ((span_or_vec).data.size / sizeof *(span_or_vec).dummy_pointer)