do not reallocate memory so often

This commit is contained in:
VaclavT 2021-08-06 22:47:42 +02:00
parent 198d91b498
commit 8d220356f2
1 changed files with 13 additions and 5 deletions

View File

@ -465,20 +465,28 @@ void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
struct abuf {
char *b;
int len;
int alloc_len;
};
static void abInit(struct abuf *ab) {
ab->b = NULL;
ab->len = 0;
ab->alloc_len = 0;
}
static void abAppend(struct abuf *ab, const char *s, int len) {
char *new = realloc(ab->b,ab->len+len);
if ( ab->alloc_len > ab->len+len) {
memcpy(ab->b+ab->len,s,len);
ab->len += len;
} else {
char *new = realloc(ab->b,ab->len+len+32);
if (new == NULL) return;
memcpy(new+ab->len,s,len);
ab->b = new;
ab->len += len;
if (new == NULL) return;
memcpy(new+ab->len,s,len);
ab->b = new;
ab->len += len;
ab->alloc_len = ab->len+32;
}
}
static void abFree(struct abuf *ab) {