You've already forked flecs_tests
History, spatial grid and optimizations
This commit is contained in:
43
src/util.h
43
src/util.h
@@ -11,11 +11,24 @@ typedef struct vector_t {
|
||||
int stride;
|
||||
} vector_t;
|
||||
|
||||
/**
|
||||
* Zero-initialize a vector with the given element stride.
|
||||
*
|
||||
* @param v vector to initialize
|
||||
* @param stride byte size of each element
|
||||
*/
|
||||
static void vec_init(vector_t *v, int stride) {
|
||||
memset(v, 0, sizeof(*v));
|
||||
v->stride = stride;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grow the vector's backing array to at least min_capacity elements.
|
||||
* Doubles capacity (starting at 8) or uses min_capacity, whichever is larger.
|
||||
*
|
||||
* @param v vector to grow
|
||||
* @param min_capacity minimum element count required
|
||||
*/
|
||||
static void vec_grow(vector_t *v, int min_capacity) {
|
||||
int new_cap = v->capacity ? v->capacity * 2 : 8;
|
||||
if (new_cap < min_capacity) new_cap = min_capacity;
|
||||
@@ -28,15 +41,33 @@ static void vec_grow(vector_t *v, int min_capacity) {
|
||||
v->capacity = new_cap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Append an uninitialized element to the end of the vector. Grows if needed.
|
||||
*
|
||||
* @param v vector to push into
|
||||
* @return pointer to the new (uninitialized) element
|
||||
*/
|
||||
static void *vec_push(vector_t *v) {
|
||||
if (v->count >= v->capacity) vec_grow(v, v->count + 1);
|
||||
return v->data + (v->count++) * v->stride;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the last element from the vector (decrements count, no free).
|
||||
*
|
||||
* @param v vector to pop from
|
||||
*/
|
||||
static void vec_pop(vector_t *v) {
|
||||
if (v->count > 0) v->count--;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the element at index by swapping in the last element (O(1)).
|
||||
* Order is not preserved.
|
||||
*
|
||||
* @param v vector to remove from
|
||||
* @param index index of the element to remove
|
||||
*/
|
||||
static void vec_remove(vector_t *v, int index) {
|
||||
if (index < 0 || index >= v->count) return;
|
||||
if (index < v->count - 1) {
|
||||
@@ -47,10 +78,22 @@ static void vec_remove(vector_t *v, int index) {
|
||||
v->count--;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a pointer to the element at index (no bounds check).
|
||||
*
|
||||
* @param v vector to access
|
||||
* @param index element index
|
||||
* @return pointer to the element
|
||||
*/
|
||||
static void *vec_get(vector_t *v, int index) {
|
||||
return v->data + index * v->stride;
|
||||
}
|
||||
|
||||
/**
|
||||
* Free the backing array and reset the vector to empty.
|
||||
*
|
||||
* @param v vector to free
|
||||
*/
|
||||
static void vec_free(vector_t *v) {
|
||||
if (v->data) FREE(v->data);
|
||||
v->data = NULL;
|
||||
|
||||
Reference in New Issue
Block a user