summaryrefslogtreecommitdiff
path: root/stalloc.c
diff options
context:
space:
mode:
Diffstat (limited to 'stalloc.c')
-rw-r--r--stalloc.c63
1 files changed, 63 insertions, 0 deletions
diff --git a/stalloc.c b/stalloc.c
new file mode 100644
index 0000000..f8abb22
--- /dev/null
+++ b/stalloc.c
@@ -0,0 +1,63 @@
+#include <stdlib.h>
+
+static int nb_pools = 0;
+static char ** mem_pools = 0;
+static size_t * pools_size = 0;
+
+#define POOL_SIZE 16384
+
+static int create_pool() {
+ nb_pools++;
+ mem_pools = (char **) realloc(mem_pools, sizeof(char *) * nb_pools);
+ pools_size = (size_t *) realloc(pools_size, sizeof(size_t) * nb_pools);
+ mem_pools[nb_pools - 1] = malloc(POOL_SIZE);
+ pools_size[nb_pools - 1] = 0;
+
+ return nb_pools - 1;
+}
+
+int search_pool(size_t s) {
+ int i;
+
+ // This algorithm could use a little bit more of cleverness, but... *shrug*
+ // the whole purpose is to be used for small static strings, so...
+ for (i = 0; i < nb_pools; i++) {
+ if (s <= (POOL_SIZE - pools_size[i]))
+ return i;
+ }
+
+ return -1;
+}
+
+void * st_alloc(size_t s) {
+ int pool;
+
+ if (s > POOL_SIZE)
+ return malloc(s);
+
+ pool = search_pool(s);
+ if (pool < 0)
+ pool = create_pool();
+
+ pools_size[pool] += s;
+
+ return mem_pools[pool] + pool_size[pool] - s;
+}
+
+char * st_strdup(const char * src) {
+ int s = strlen(src) + 1;
+ char * r = (char *) st_alloc(s)
+ memcpy(r, src);
+
+ return r;
+}
+
+void st_shutdown() {
+ int i;
+
+ for (i = 0; i < nb_pools; i++) {
+ free(mem_pools[i]);
+ }
+ free(mem_pools);
+ free(pools_size);
+}