aboutsummaryrefslogtreecommitdiff
path: root/src/vec.c
diff options
context:
space:
mode:
authorKimplul <kimi.h.kuparinen@gmail.com>2024-04-20 03:39:40 +0300
committerKimplul <kimi.h.kuparinen@gmail.com>2024-04-20 03:39:40 +0300
commit1cc7990ef7d5483d0434dda412f2d88e0b17df27 (patch)
tree93c9945318908c4f593251c0b8f9ecf57c3bde96 /src/vec.c
parentedf56e3444d5333d4362277ee97a5cdf0c2f52af (diff)
downloadposthaste-1cc7990ef7d5483d0434dda412f2d88e0b17df27.tar.gz
posthaste-1cc7990ef7d5483d0434dda412f2d88e0b17df27.zip
initial working bytecode
Diffstat (limited to 'src/vec.c')
-rw-r--r--src/vec.c75
1 files changed, 75 insertions, 0 deletions
diff --git a/src/vec.c b/src/vec.c
new file mode 100644
index 0000000..3fc2d7d
--- /dev/null
+++ b/src/vec.c
@@ -0,0 +1,75 @@
+#include <stdlib.h>
+#include <assert.h>
+#include <string.h>
+
+#include <posthaste/vec.h>
+
+struct vec vec_create(size_t ns)
+{
+ return (struct vec) {
+ .n = 0,
+ .s = 1,
+ .ns = ns,
+ .buf = malloc(ns),
+ };
+}
+
+size_t vec_len(struct vec *v)
+{
+ return v->n;
+}
+
+void *vec_at(struct vec *v, size_t i)
+{
+ assert(i < v->n && "out of vector bounds");
+ return v->buf + i * v->ns;
+}
+
+void *vec_back(struct vec *v)
+{
+ assert(v->n);
+ return v->buf + (v->n - 1) * v->ns;
+}
+
+void *vec_pop(struct vec *v)
+{
+ assert(v->n && "attempting to pop empty vector");
+ v->n--;
+ return v->buf + v->n * v->ns;
+}
+
+void vec_append(struct vec *v, void *n)
+{
+ v->n++;
+ if (v->n >= v->s) {
+ v->s *= 2;
+ v->buf = realloc(v->buf, v->s * v->ns);
+ }
+
+ void *p = vec_at(v, v->n - 1);
+ memcpy(p, n, v->ns);
+}
+
+void vec_reset(struct vec *v)
+{
+ v->n = 0;
+}
+
+void vec_reserve(struct vec *v, size_t n)
+{
+ if (v->n >= n)
+ return;
+
+ v->n = n;
+ v->s = n;
+ v->buf = realloc(v->buf, v->s * v->ns);
+}
+
+void vec_destroy(struct vec *v) {
+ free(v->buf);
+}
+
+void vec_sort(struct vec *v, vec_comp_t comp)
+{
+ qsort(v->buf, v->n, v->ns, comp);
+}