add assignment operator and unify memory pools

The unification of memory pools also fixed some memory leaks and
hopefully reduced the mallocs of identifier strings significantly by
giving them the same pool as the token stream.
This commit is contained in:
r4
2021-12-21 11:40:49 +01:00
parent 21694f98ac
commit 63af3e907b
11 changed files with 121 additions and 48 deletions

39
util.c
View File

@@ -49,6 +49,38 @@ void set_err(const char *fmt, ...) {
va_end(va);
}
Pool *pool_new(size_t init_cap) {
Pool *p = malloc(sizeof(Pool) + init_cap);
p->len = 0;
p->cap = init_cap;
p->data = p + 1;
p->next = NULL;
return p;
}
void pool_term(Pool *p) {
for (Pool *i = p; i != NULL;) {
Pool *next = i->next;
free(i);
i = next;
}
}
void *pool_alloc(Pool *p, size_t bytes) {
for (Pool *i = p;; i = i->next) {
if (i->len + bytes < i->cap) {
void *ret = (uint8_t*)i->data + i->len;
i->len += bytes;
return ret;
}
if (!i->next) {
i->next = pool_new(bytes + i->cap * 2);
i->next->len = bytes;
return i->next->data;
}
}
}
char *sndup(const char *s, size_t n) {
char *ret = malloc(n+1);
if (ret) {
@@ -58,6 +90,13 @@ char *sndup(const char *s, size_t n) {
return ret;
}
char *psndup(Pool *p, const char *s, size_t n) {
char *ret = pool_alloc(p, n+1);
memcpy(ret, s, n);
ret[n] = 0;
return ret;
}
intmax_t stoimax(const char *s, size_t n, size_t base, ssize_t *endpos) {
for (size_t i = 0; i < n; i++) { if (s[i] == 0) { n = i; break; } }
intmax_t res = 0;