diff --git a/include/ref_vec.h b/include/ref_vec.h index e81f265..85c2d8f 100644 --- a/include/ref_vec.h +++ b/include/ref_vec.h @@ -34,6 +34,13 @@ typedef struct libab_ref_vec_s libab_ref_vec; * @return the result of the initialization. */ libab_result libab_ref_vec_init(libab_ref_vec* vec); +/** + * Initializes a new vector as a copy another. + * @param vec the vector to initialize. + * @param copy_of the vector to make a copy of. + * @return the result of the initialization. + */ +libab_result libab_ref_vec_init_copy(libab_ref_vec* vec, libab_ref_vec* copy_of); /** * Inserts an existing reference counted value into the vector. * This bumps the reference's refcount, thereby preventing its @@ -61,6 +68,11 @@ libab_result libab_ref_vec_insert_value(libab_ref_vec* vec, void* data, * @return the reference stored at the given index. */ void libab_ref_vec_index(libab_ref_vec* vec, size_t index, libab_ref* into); +/** + * Clears the reference counted vector, without resizing. + * @param vec the vector to clear. + */ +void libab_ref_vec_clear(libab_ref_vec* vec); /** * Releases the memory allocated by the vector. * The references stored in the vector have their refcount decreased. diff --git a/src/ref_vec.c b/src/ref_vec.c index 65a19d7..d9782f3 100644 --- a/src/ref_vec.c +++ b/src/ref_vec.c @@ -12,6 +12,21 @@ libab_result libab_ref_vec_init(libab_ref_vec* vec) { return result; } +libab_result libab_ref_vec_init_copy(libab_ref_vec* vec, libab_ref_vec* copy_of) { + libab_result result = LIBAB_SUCCESS; + if((vec->data = malloc(sizeof(*vec->data) * copy_of->capacity))) { + size_t index = 0; + vec->size = copy_of->size; + vec->capacity = copy_of->capacity; + for(; index < copy_of->size; index++) { + libab_ref_copy(©_of->data[index], &vec->data[index]); + } + } else { + result = LIBAB_MALLOC; + } + return result; +} + libab_result _libab_ref_vec_try_resize(libab_ref_vec* vec) { libab_result result = LIBAB_SUCCESS; if (vec->size == vec->capacity) { @@ -58,6 +73,14 @@ void libab_ref_vec_index(libab_ref_vec* vec, size_t index, libab_ref* into) { } } +void libab_ref_vec_clear(libab_ref_vec* vec) { + size_t i = 0; + for(; i < vec->size; i++) { + libab_ref_free(&vec->data[i]); + } + vec->size = 0; +} + void libab_ref_vec_free(libab_ref_vec* vec) { size_t i = 0; for (; i < vec->size; i++) {