summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--include/qemu/buffer.h10
-rw-r--r--util/buffer.c20
2 files changed, 29 insertions, 1 deletions
diff --git a/include/qemu/buffer.h b/include/qemu/buffer.h
index 1358df1..0a69b3a 100644
--- a/include/qemu/buffer.h
+++ b/include/qemu/buffer.h
@@ -52,6 +52,16 @@ void buffer_init(Buffer *buffer, const char *name, ...)
GCC_FMT_ATTR(2, 3);
/**
+ * buffer_shrink:
+ * @buffer: the buffer object
+ *
+ * Try to shrink the buffer. Checks current buffer capacity and size
+ * and reduces capacity in case only a fraction of the buffer is
+ * actually used.
+ */
+void buffer_shrink(Buffer *buffer);
+
+/**
* buffer_reserve:
* @buffer: the buffer object
* @len: the minimum required free space
diff --git a/util/buffer.c b/util/buffer.c
index e8f798e..234e33d 100644
--- a/util/buffer.c
+++ b/util/buffer.c
@@ -20,7 +20,8 @@
#include "qemu/buffer.h"
-#define BUFFER_MIN_INIT_SIZE 4096
+#define BUFFER_MIN_INIT_SIZE 4096
+#define BUFFER_MIN_SHRINK_SIZE 65536
void buffer_init(Buffer *buffer, const char *name, ...)
{
@@ -31,6 +32,23 @@ void buffer_init(Buffer *buffer, const char *name, ...)
va_end(ap);
}
+void buffer_shrink(Buffer *buffer)
+{
+ /*
+ * Only shrink in case the used size is *much* smaller than the
+ * capacity, to avoid bumping up & down the buffers all the time.
+ * realloc() isn't exactly cheap ...
+ */
+ if (buffer->offset < (buffer->capacity >> 3) &&
+ buffer->capacity > BUFFER_MIN_SHRINK_SIZE) {
+ return;
+ }
+
+ buffer->capacity = pow2ceil(buffer->offset);
+ buffer->capacity = MAX(buffer->capacity, BUFFER_MIN_SHRINK_SIZE);
+ buffer->buffer = g_realloc(buffer->buffer, buffer->capacity);
+}
+
void buffer_reserve(Buffer *buffer, size_t len)
{
if ((buffer->capacity - buffer->offset) < len) {
OpenPOWER on IntegriCloud