aboutsummaryrefslogtreecommitdiff
path: root/src/res.c
diff options
context:
space:
mode:
authorKimplul <kimi.h.kuparinen@gmail.com>2023-03-07 02:18:26 +0200
committerKimplul <kimi.h.kuparinen@gmail.com>2023-03-07 02:18:26 +0200
commitae5fee63f160643a397d18e9e0658275606bc4d4 (patch)
treef68af302374f9ae3c9dbb28dab5547036252d559 /src/res.c
downloadek-ae5fee63f160643a397d18e9e0658275606bc4d4.tar.gz
ek-ae5fee63f160643a397d18e9e0658275606bc4d4.zip
initial commit
Diffstat (limited to 'src/res.c')
-rw-r--r--src/res.c60
1 files changed, 60 insertions, 0 deletions
diff --git a/src/res.c b/src/res.c
new file mode 100644
index 0000000..787f50a
--- /dev/null
+++ b/src/res.c
@@ -0,0 +1,60 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later */
+
+/**
+ * @file res.c
+ * Simple resource manager implementation.
+ */
+
+#include <stdint.h>
+#include <stdlib.h>
+
+#include <ct/res.h>
+
+/**
+ * Grow resource manager buffer.
+ * Doubles every call.
+ *
+ * @param r Resource manager to expand.
+ */
+static void res_expand(struct res *r)
+{
+ r->max *= 2;
+ r->p = realloc(r->p, r->max * sizeof(void *));
+}
+
+struct res *res_create()
+{
+ struct res *r = malloc(sizeof(struct res));
+ r->n = 0;
+ /* arbitrary number */
+ r->max = 1024;
+ r->p = calloc(1, r->max * sizeof(void *));
+ return r;
+}
+
+void res_add(struct res *r, void *p)
+{
+ if (r->n >= r->max)
+ res_expand(r);
+
+ r->p[r->n++] = p;
+}
+
+void *res_alloc(struct res *r, size_t size)
+{
+ void *p = malloc(size);
+ if (!p)
+ return NULL;
+
+ res_add(r, p);
+ return p;
+}
+
+void res_destroy(struct res *r)
+{
+ for (size_t i = 0; i < r->n; ++i)
+ free(r->p[i]);
+
+ free(r->p);
+ free(r);
+}