From f76c8ad30bd9afb60ba9071817f56cb04309d5eb Mon Sep 17 00:00:00 2001 From: Dominique Martinet Date: Mon, 17 Sep 2018 11:01:24 +0900 Subject: [PATCH] pager history buffer: alloc buffer progressively Realloc buffer 1MB at a time until the configured size is reached --- kitty/data-types.h | 2 +- kitty/history.c | 19 ++++++++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/kitty/data-types.h b/kitty/data-types.h index c07122830..a7519a3ee 100644 --- a/kitty/data-types.h +++ b/kitty/data-types.h @@ -174,7 +174,7 @@ typedef struct { } HistoryBufSegment; typedef struct { - index_type bufsize; + index_type bufsize, maxsz; Py_UCS4 *buffer; index_type start, end; index_type bufend; diff --git a/kitty/history.c b/kitty/history.c index 1b84a83aa..740aefe33 100644 --- a/kitty/history.c +++ b/kitty/history.c @@ -60,12 +60,23 @@ alloc_pagerhist(unsigned int pagerhist_sz) { if (!pagerhist_sz) return NULL; pagerhist_sz *= 1024*1024; ph = PyMem_Calloc(1, sizeof(PagerHistoryBuf)); - ph->bufsize = pagerhist_sz / sizeof(Py_UCS4); - ph->buffer = PyMem_RawMalloc(pagerhist_sz); + ph->maxsz = pagerhist_sz / sizeof(Py_UCS4); + ph->bufsize = 1024*1024 / sizeof(Py_UCS4); + ph->buffer = PyMem_RawMalloc(1024*1024); if (!ph->buffer) { PyMem_Free(ph); return NULL; } return ph; } +static inline bool +pagerhist_extend(PagerHistoryBuf *ph) { + if (ph->bufsize >= ph->maxsz) return false; + void *newbuf = PyMem_Realloc(ph->buffer, ph->bufsize * sizeof(Py_UCS4) + 1024*1024); + if (!newbuf) return false; + ph->buffer = newbuf; + ph->bufsize += 1024*1024 / sizeof(Py_UCS4); + return true; +} + static PyObject * new(PyTypeObject *type, PyObject *args, PyObject UNUSED *kwds) { HistoryBuf *self; @@ -156,7 +167,9 @@ pagerhist_push(HistoryBuf *self) { if (ph->start != ph->end && !l.continued) { ph->buffer[ph->end++] = '\n'; } - if (ph->bufsize - ph->end < 1024) { ph->bufend = ph->end; ph->end = 0; } + if (ph->bufsize - ph->end < 1024 && !pagerhist_extend(ph)) { + ph->bufend = ph->end; ph->end = 0; + } ph->end += line_as_ansi(&l, ph->buffer + ph->end, 1023); ph->buffer[ph->end++] = '\r'; if (ph->bufend) {