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:
39
util.c
39
util.c
@@ -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;
|
||||
|
Reference in New Issue
Block a user