aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTucker Evans <tucker@tuckerevans.com>2020-07-02 19:07:46 -0400
committerTucker Evans <tucker@tuckerevans.com>2020-07-02 19:42:13 -0400
commit264857903db99135c8c09d12b3e8af93ac1c7f88 (patch)
tree9c18cdd8960ed7c5202a53657c04169d0254bbc3
parent0d09851c392829a6cbbd047f9a374b5c66eb4c98 (diff)
Add index functionality to vectors
-rw-r--r--collections/vector/vector.adoc25
-rw-r--r--collections/vector/vector.c11
-rw-r--r--collections/vector/vector.h1
3 files changed, 36 insertions, 1 deletions
diff --git a/collections/vector/vector.adoc b/collections/vector/vector.adoc
index cf001d3..1dce41b 100644
--- a/collections/vector/vector.adoc
+++ b/collections/vector/vector.adoc
@@ -1,7 +1,7 @@
Vector
======
Tucker Evans
-v0.2, 2020-07-02
+v0.3, 2020-07-02
A basic vector, that hold pointers to your data structures.
@@ -78,3 +78,26 @@ vec *vector = vec_new();
vec_push(vector, NULL);
assert(vec_size(vector) == 1);
----
+
++void* vec_index(vec *self, int index)+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Returns the element at position +index+ of +self+.
+
+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_push(vector, str_dup(str3));
+
+assert(str_cmp(vec_index(vector, 1), str2) == 0);
+----
diff --git a/collections/vector/vector.c b/collections/vector/vector.c
index afe99de..9d895d5 100644
--- a/collections/vector/vector.c
+++ b/collections/vector/vector.c
@@ -75,3 +75,14 @@ void *item;
root->base[root->end++] = item;
}
+
+void* vec_index(root, index)
+vec *root;
+int index;
+{
+ if (!root || index >= root->end || index < 0) {
+ return NULL;
+ }
+
+ return root->base[index];
+}
diff --git a/collections/vector/vector.h b/collections/vector/vector.h
index b84217a..63151ac 100644
--- a/collections/vector/vector.h
+++ b/collections/vector/vector.h
@@ -7,4 +7,5 @@ vec* vec_new();
vec* vec_with_capacity(int);
int vec_size(vec*);
void vec_push(vec*, void*);
+void* vec_index(vec*, int);
#endif