From 2661812e3fc3f7385a5f8343172afc173f594efe Mon Sep 17 00:00:00 2001 From: Pixel Date: Tue, 17 Feb 2009 02:28:08 +0100 Subject: Adding stalloc system. --- stalloc.c | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 stalloc.c (limited to 'stalloc.c') 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 + +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); +} -- cgit v1.2.3