src/buffer.c

changeset 1290
4ac889e14211
parent 1288
b41ad5d9bcbf
child 1291
5942859fd76c
--- a/src/buffer.c	Sun Apr 13 12:30:18 2025 +0200
+++ b/src/buffer.c	Sun Apr 13 13:02:54 2025 +0200
@@ -209,6 +209,28 @@
     }
 }
 
+void cxBufferShrink(
+        CxBuffer *buffer,
+        size_t reserve
+) {
+    // Ensure buffer is in a reallocatable state
+    const int force_copy_flags = CX_BUFFER_COPY_ON_WRITE | CX_BUFFER_COPY_ON_EXTEND;
+    if (buffer->flags & force_copy_flags) {
+        // do nothing when we are not allowed to reallocate
+        return;
+    }
+
+    // calculate new capacity
+    size_t newCapacity = buffer->size + reserve;
+
+    // If new capacity is smaller than current capacity, resize the buffer
+    if (newCapacity < buffer->capacity) {
+        if (0 == cxReallocate(buffer->allocator, &buffer->bytes, newCapacity)) {
+            buffer->capacity = newCapacity;
+        }
+    }
+}
+
 static size_t cx_buffer_flush_helper(
         const CxBuffer *buffer,
         const unsigned char *src,

mercurial