buffer: add buffer_shrink
authorGerd Hoffmann <kraxel@redhat.com>
Fri, 30 Oct 2015 11:10:00 +0000 (12:10 +0100)
committerGerd Hoffmann <kraxel@redhat.com>
Thu, 5 Nov 2015 08:08:41 +0000 (09:08 +0100)
Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>
Reviewed-by: Peter Lieven <pl@kamp.de>
Reviewed-by: Daniel P. Berrange <berrange@redhat.com>
Message-id: 1446203414-4013-6-git-send-email-kraxel@redhat.com

include/qemu/buffer.h
util/buffer.c

index 1358df1aac4e1a2164fc4064536fcb5f348c92ef..0a69b3a97224cbcb519a59937a39e45cc0beb75d 100644 (file)
@@ -51,6 +51,16 @@ struct Buffer {
 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
index e8f798e62010d60aa259f1d31a124639b2812b45..234e33d5c1692a8c5eb05098f7356cd1e630a20e 100644 (file)
@@ -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) {