commit 27bfa1b56b9959562be1cb7463833a8023d5d047
parent a169bc9ed6aad8ecf8e6ce1e89b2924f5c46b072
Author: glenda <glenda@9front.local>
Date: Thu, 12 Aug 2021 16:48:55 +0000
do commit array source files
Diffstat:
A | array.c | | | 47 | +++++++++++++++++++++++++++++++++++++++++++++++ |
A | array.h | | | 14 | ++++++++++++++ |
2 files changed, 61 insertions(+), 0 deletions(-)
diff --git a/array.c b/array.c
@@ -0,0 +1,47 @@
+#include <u.h>
+#include <libc.h>
+
+#include "array.h"
+
+Array *
+arraycreate(usize size, long n, void (*free)(void *))
+{
+ Array *ap;
+ ap = mallocz(sizeof(Array), 1);
+ ap->size = size;
+ ap->count = 0;
+ ap->n = n;
+ ap->mem = mallocz(size * n, 1);
+ ap->free = free;
+ return ap;
+}
+
+void
+arrayfree(Array *ap)
+{
+ int i;
+ if (ap->free != nil) {
+ for (i = 0; i < ap->count; i ++) {
+ void *v;
+ v = arrayget(ap, i);
+ ap->free(v);
+ }
+ }
+ free(ap);
+ /* stub */
+}
+
+void *
+arrayadd(Array *ap)
+{
+ ap->count++;
+ if (ap->count > ap->n) ap->n += ap->n;
+ ap->mem = realloc(ap->mem, ap->size * ap->n);
+ return memset(arrayget(ap, ap->count - 1), 0, ap->size);
+}
+
+void *
+arrayget(Array *ap, long n)
+{
+ return (void *)(ap->mem + ap->size * n);
+}
diff --git a/array.h b/array.h
@@ -0,0 +1,14 @@
+typedef struct Array Array;
+
+struct Array {
+ usize size;
+ usize n;
+ long count;
+ char *mem;
+ void (*free)(void *);
+};
+
+Array * arraycreate(usize, long, void (*free)(void *));
+void arrayfree(Array *);
+void * arrayadd(Array *);
+void * arrayget(Array *, long);