aboutsummaryrefslogtreecommitdiff
path: root/collections
diff options
context:
space:
mode:
authorTucker Evans <tucker@tuckerevans.com>2020-07-03 23:49:15 -0400
committerTucker Evans <tucker@tuckerevans.com>2020-07-04 23:13:34 -0400
commite6af2f70ec910ee8cb3813fa1e5b1c7d6e3ead60 (patch)
treead518b44f3a1eb0601a1b52ca59cc55a61b16e72 /collections
parenta691f4d4b0a57d62eb792e6ede0c0fa5334e3e61 (diff)
Add insert function for vectors
Diffstat (limited to 'collections')
-rw-r--r--collections/vector/vector.adoc29
-rw-r--r--collections/vector/vector.c17
-rw-r--r--collections/vector/vector.h2
3 files changed, 47 insertions, 1 deletions
diff --git a/collections/vector/vector.adoc b/collections/vector/vector.adoc
index ee453ff..9e61a43 100644
--- a/collections/vector/vector.adoc
+++ b/collections/vector/vector.adoc
@@ -1,7 +1,7 @@
Vector
======
Tucker Evans
-v0.12, 2020-07-03
+v0.13, 2020-07-03
A basic vector, that hold pointers to your data structures.
@@ -257,6 +257,33 @@ vec_push(vector, str_dup(str3));
assert(str_cmp(vec_index(vector, 1), str2) == 0);
----
+[[vec_insert]]
++void vec_insert(vec *self, int index, void *item)+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Inserts +item+ into vector +self+ at index +index+, all items after the index
+are pushed toward the end.
+
+Examples
+^^^^^^^^
+[source,c]
+----
+#include "vector.h"
+#include <string.h>
+
+char *str1 = "ONE";
+char *str2 = "TWO";
+char *str3 = "THREE";
+
+vec *vector = vec_new();
+vec_push(vector, str_dup(str1));
+vec_push(vector, str_dup(str2));
+
+vec_insert(vector, 1, str_dup(str3));
+
+assert(str_cmp(vec_index(vector, 1), str3) == 0);
+assert(str_cmp(vec_index(vector, 2), str2) == 0);
+----
+
[[vec_swap]]
+void vec_swap(vec *self, int i, int j)+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/collections/vector/vector.c b/collections/vector/vector.c
index 79e31a4..2ae748f 100644
--- a/collections/vector/vector.c
+++ b/collections/vector/vector.c
@@ -174,6 +174,23 @@ int index;
return root->base[index];
}
+void vec_insert(root, index, item)
+vec *root;
+int index;
+void *item;
+{
+ if (!root || index > root->end || index < 0)
+ return;
+
+ if (root->end >= root->limit)
+ vec_resize(root);
+
+ memmove(root->base + index + 1, root->base + index,
+ (root->end++ - index) * sizeof(void*));
+
+ root->base[index] = item;
+}
+
void vec_swap(root, i, j)
vec *root;
int i,j;
diff --git a/collections/vector/vector.h b/collections/vector/vector.h
index 55e9481..1b47642 100644
--- a/collections/vector/vector.h
+++ b/collections/vector/vector.h
@@ -21,6 +21,8 @@ void* vec_back(vec*);
void vec_set(vec*, int, void*);
void* vec_index(vec*, int);
+void vec_insert(vec*, int, void*);
+
void vec_swap(vec*, int, int);
void* vec_swap_pop(vec*, int);