diff options
author | Tucker Evans <tucker@tuckerevans.com> | 2020-07-03 00:13:04 -0400 |
---|---|---|
committer | Tucker Evans <tucker@tuckerevans.com> | 2020-07-04 22:29:31 -0400 |
commit | 8d5b381b540fe1d780311e4f4059dce014a6cb91 (patch) | |
tree | b43273bc4c2b9d20baadf9f2c35948888fab6619 | |
parent | 80d98a39a6bc4b71c74f240df617495e816b98b9 (diff) |
Add copy function for vector
-rw-r--r-- | collections/vector/vector.adoc | 26 | ||||
-rw-r--r-- | collections/vector/vector.c | 20 | ||||
-rw-r--r-- | collections/vector/vector.h | 1 |
3 files changed, 46 insertions, 1 deletions
diff --git a/collections/vector/vector.adoc b/collections/vector/vector.adoc index fbb0b32..4920893 100644 --- a/collections/vector/vector.adoc +++ b/collections/vector/vector.adoc @@ -1,7 +1,7 @@ Vector ====== Tucker Evans -v0.6, 2020-07-02 +v0.7, 2020-07-03 A basic vector, that hold pointers to your data structures. @@ -212,3 +212,27 @@ Output: VEC_CONTENTS: [ONE,TWO,THREE] ---- + +[[vec_cp]] ++vec* vec_cp(vec *self)+ +~~~~~~~~~~~~~~~~~~~~~~~~ +Returns a copy of the vector +self+. All elements are kept in the same order. + +Examples +^^^^^^^^ +[source,c] +---- +#include "vector.h" +#include <string.h> + +char *str1 = "ONE"; +char *str2 = "TWO"; + +vec *vector = vec_with_capacity(16); +vec_push_back(vector, str_dup(str1)); +vec_push_back(vector, str_dup(str2)); + +vec *new = vec_cp(vector); +assert(strcmp(vec_pop_back, str2) == 0); +assert(strcmp(vec_pop_back, str1) == 0); +---- diff --git a/collections/vector/vector.c b/collections/vector/vector.c index b3751dd..8aaffb6 100644 --- a/collections/vector/vector.c +++ b/collections/vector/vector.c @@ -144,3 +144,23 @@ vec *root; } fprintf(stderr, "\n"); } + +vec* vec_cp(root) +vec *root; +{ + vec *copy; + + if (!root) + return NULL; + + copy = vec_with_capacity(root->limit); + + copy->base = memcpy(copy->base, root->base, + vec_size(root) * sizeof(void*)); + assert(copy->base); + + copy->end = root->end; + copy->limit = root->limit; + + return copy; +} diff --git a/collections/vector/vector.h b/collections/vector/vector.h index 54e40a7..229b4b0 100644 --- a/collections/vector/vector.h +++ b/collections/vector/vector.h @@ -12,4 +12,5 @@ void* vec_pop(vec*); void vec_free(vec*); void vec_clear(vec*); void vec_print(vec*, char* (void*)); +vec* vec_cp(vec*); #endif |