diff options
author | Tucker Evans <tucker@tuckerevans.com> | 2020-07-04 22:17:27 -0400 |
---|---|---|
committer | Tucker Evans <tucker@tuckerevans.com> | 2020-07-04 23:14:34 -0400 |
commit | 5fa1551b4a0acc28d5c656479806511ab0c81a18 (patch) | |
tree | 47738892753aaf5947f011f779efd159ea476266 | |
parent | 8aa9f42d914a453a0570752ee292b9a9cfcae9d6 (diff) |
Add reserve function to vectors
-rw-r--r-- | collections/vector/vector.adoc | 20 | ||||
-rw-r--r-- | collections/vector/vector.c | 14 | ||||
-rw-r--r-- | collections/vector/vector.h | 1 |
3 files changed, 34 insertions, 1 deletions
diff --git a/collections/vector/vector.adoc b/collections/vector/vector.adoc index ce91c71..7c4bc7f 100644 --- a/collections/vector/vector.adoc +++ b/collections/vector/vector.adoc @@ -1,7 +1,7 @@ Vector ====== Tucker Evans -v0.16, 2020-07-04 +v0.17, 2020-07-04 A basic vector, that hold pointers to your data structures. @@ -400,6 +400,24 @@ vec_truncate(vector, 1); assert(vec_size == 1); ---- +[[vec_reserve]] ++void vec_reserve(vec *self, int additional)+ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Reserves space for +additional+ items. May reserve more memory to avoid too +many reallocations. + +Examples +^^^^^^^^ +[source,c] +---- +#include "vector.h" + +vec *vector = vec_with_capacity(16); + +vec_reserve(vector, 20); +assert(vec_capacity(vector) >= 20); +---- + [[vec_clear]] +void vec_clear(vec *self)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/collections/vector/vector.c b/collections/vector/vector.c index 391b5a6..f14c302 100644 --- a/collections/vector/vector.c +++ b/collections/vector/vector.c @@ -250,6 +250,20 @@ int size; root->end = size; } +void vec_reserve(root, n) +vec *root; +int n; +{ + int i; + + if (!root || n + root->end <= root->limit) + return; + + for (i = root->limit; i < root->end + n; i*=2); + + root->base = reallocarray(root->base, i, sizeof(void*)); +} + void vec_clear(root) vec *root; { diff --git a/collections/vector/vector.h b/collections/vector/vector.h index b997b46..4d6d04c 100644 --- a/collections/vector/vector.h +++ b/collections/vector/vector.h @@ -30,6 +30,7 @@ void* vec_swap_pop(vec*, int); /*memory*/ void vec_truncate(vec*, int); +void vec_reserve(vec*, int); void vec_clear(vec*); void vec_free(vec*); |