Skip to content

Commit

Permalink
refactor: destroy and destroy_ptr for vec
Browse files Browse the repository at this point in the history
  • Loading branch information
jenspots committed Apr 13, 2024
1 parent 6b567ec commit fafcaf2
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 15 deletions.
27 changes: 26 additions & 1 deletion include/wheel/vec/header.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,36 @@

typedef struct vec vec;

/**
* Initialize a new vector with the default capacity.
* @note The default capacity is defined by LIBWHEEL_INITIAL_SIZE.
* @return A stack allocated vector.
* @see vec_init_ptr for a heap allocated vector.
*/
vec vec_init();

/**
* Initialize a new vector with the default capacity.
* @note The default capacity is defined by LIBWHEEL_INITIAL_SIZE.
* @return A heap allocated vector.
* @see `vec_init` for a stack allocated vector.
*/
vec* vec_init_ptr();

/**
* Destroy a stack-allocated vector and free its memory.
* @param v The vector to destroy.
* @see `vec_destroy_ptr` for heap allocated vectors.
*/
void vec_destroy(vec* v);

/**
* Destroy a heap-allocated vector and free its memory.
* @param v The vector to destroy.
* @see `vec_destroy` for stack allocated vectors.
*/
void vec_destroy_ptr(vec** v);

vec vec_with_cap(uint64_t capacity);

#ifdef LIBWHEEL_TRAIT_SHALLOW_COPY
Expand All @@ -16,7 +42,6 @@ LIBWHEEL_TYPE* vec_get_ptr(const vec* v, uint64_t index);

optional vec_pop(vec* v, uint64_t index);

void vec_destroy(vec* v);

void vec_grow(vec* v);

Expand Down
39 changes: 25 additions & 14 deletions include/wheel/vec/impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,31 @@ vec* vec_init_ptr() {
return v;
}

void vec_destroy(vec* v) {
assert(v);
assert(v->values);

for (uint64_t i = 0; i < v->size; ++i) {
if (vec_bit_get(&v->present, i)) {
trait_destroy(v->values[i]);
}
}

free(v->values);
vec_bit_destroy(&v->present);
}

void vec_destroy_ptr(vec** v) {
assert(v);
assert(*v);

// Remove the underlying vector.
vec_destroy(*v);

// Free the allocated memory and set the pointer to null.
free(*v);
*v = NULL;
}

vec vec_with_cap(uint64_t capacity) {
assert(capacity > 0);
Expand Down Expand Up @@ -97,20 +122,6 @@ optional vec_pop(vec* v, uint64_t index) {
return result;
}

void vec_destroy(vec* v) {
assert(v);
assert(v->values);

for (uint64_t i = 0; i < v->size; ++i) {
if (vec_bit_get(&v->present, i)) {
trait_destroy(v->values[i]);
}
}

free(v->values);
vec_bit_destroy(&v->present);
}

void vec_grow(vec* v) {
assert(v);
assert(v->values);
Expand Down

0 comments on commit fafcaf2

Please sign in to comment.