aboutsummaryrefslogtreecommitdiff
path: root/src/alloc.c
diff options
context:
space:
mode:
authorOnur Gündüz <ogunduz@gmail.com>2026-06-16 17:11:55 +0200
committerOnur Gündüz <ogunduz@gmail.com>2026-06-16 17:11:55 +0200
commitcca81e59a9afeebe1237f713e919b5002df3d749 (patch)
treeae4ab593bfcec8208db9c912cc7712372473ef5a /src/alloc.c
parent51a716cc7bc555d765cf4ab97c6ee4935683d129 (diff)
downloadffwd-cca81e59a9afeebe1237f713e919b5002df3d749.tar.gz
ffwd-cca81e59a9afeebe1237f713e919b5002df3d749.zip
cpu: extract alloc.{c,h} and vec.c from embed.c
Diffstat (limited to '')
-rw-r--r--src/alloc.c89
1 files changed, 89 insertions, 0 deletions
diff --git a/src/alloc.c b/src/alloc.c
new file mode 100644
index 0000000..e3b82d7
--- /dev/null
+++ b/src/alloc.c
@@ -0,0 +1,89 @@
+#include "alloc.h"
+
+#include <stdlib.h>
+#include <stdint.h>
+#include <limits.h>
+
+/* Sequence-capacity growth policy for the forward-pass workspaces: never
+ * allocate fewer than the minimum, and round up to the granularity so small
+ * length changes do not trigger a realloc on every call. */
+#define EMBED_MIN_WORKSPACE_SEQ_CAP 16
+#define EMBED_WORKSPACE_SEQ_GRANULARITY 16
+
+int mul_size(size_t a, size_t b, size_t *out) {
+ if (a != 0 && b > SIZE_MAX / a)
+ return -1;
+ *out = a * b;
+ return 0;
+}
+
+int add_size(size_t a, size_t b, size_t *out) {
+ if (b > SIZE_MAX - a)
+ return -1;
+ *out = a + b;
+ return 0;
+}
+
+int grow_cap(int current, int needed, int *out) {
+ if (needed <= 0)
+ return -1;
+
+ int cap = needed;
+ if (cap < EMBED_MIN_WORKSPACE_SEQ_CAP)
+ cap = EMBED_MIN_WORKSPACE_SEQ_CAP;
+
+ int rem = cap % EMBED_WORKSPACE_SEQ_GRANULARITY;
+ if (rem != 0) {
+ int add = EMBED_WORKSPACE_SEQ_GRANULARITY - rem;
+ if (cap > INT_MAX - add)
+ return -1;
+ cap += add;
+ }
+
+ if (cap < current)
+ cap = current;
+
+ *out = cap;
+ return 0;
+}
+
+int realloc_floats(float **ptr, size_t count) {
+ size_t bytes;
+ if (mul_size(count, sizeof(float), &bytes) != 0)
+ return -1;
+
+ void *p = realloc(*ptr, bytes);
+ if (!p && bytes != 0)
+ return -1;
+ *ptr = (float *)p;
+ return 0;
+}
+
+float *malloc_floats(size_t count) {
+ size_t bytes;
+ if (mul_size(count, sizeof(float), &bytes) != 0)
+ return NULL;
+ return (float *)malloc(bytes);
+}
+
+int realloc_floats_2d(float **ptr, int rows, int cols) {
+ if (rows < 0 || cols < 0)
+ return -1;
+
+ size_t count;
+ if (mul_size((size_t)rows, (size_t)cols, &count) != 0)
+ return -1;
+ return realloc_floats(ptr, count);
+}
+
+int realloc_ints(int **ptr, size_t count) {
+ size_t bytes;
+ if (mul_size(count, sizeof(int), &bytes) != 0)
+ return -1;
+
+ void *p = realloc(*ptr, bytes);
+ if (!p && bytes != 0)
+ return -1;
+ *ptr = (int *)p;
+ return 0;
+}