diff -r 2e8edba252a0 -r 4ac889e14211 docs/Writerside/topics/buffer.h.md --- a/docs/Writerside/topics/buffer.h.md Sun Apr 13 12:30:18 2025 +0200 +++ b/docs/Writerside/topics/buffer.h.md Sun Apr 13 13:02:54 2025 +0200 @@ -117,6 +117,29 @@ and the function `cxBufferFree()` is to be used when the buffer was created with `cxBufferCreate()`. The only difference is, that `cxBufferFree()` additionally deallocates the memory of the `CxBuffer` structure. +## Capacity Management + +```C +#include + +int cxBufferMinimumCapacity(CxBuffer *buffer, size_t capacity); + +void cxBufferShrink(CxBuffer *buffer, size_t reserve); +``` + +The function `cxBufferMinimumCapacity()` guarantees a buffer capacity of _at least_ `capacity`. +It may allocate more space, depending on the allocation strategy. +The function returns non-zero if increasing the capacity was attempted unsuccessfully. + +The function `cxBufferShrink()` can be used to shrink the capacity of the buffer to its current size +plus a number of `reserve` bytes. +If the current capacity is not larger than the size plus the reserve bytes, the function will do nothing. + +> If the buffer is in a copy-on-write state, `cxBufferMinimumCapacity()` will perform the copy-on-write action +> before reallocating the space. +> The function `cxBufferShrink()` on the other hand does _nothing_ when the buffer is in a copy-on-write state, +> because it does not make much sense to copy the memory just to have it in a smaller memory region. + ## Write ```C @@ -133,8 +156,6 @@ size_t cxBufferAppend(const void *ptr, size_t size, size_t nitems, CxBuffer *buffer); - -int cxBufferMinimumCapacity(CxBuffer *buffer, size_t capacity); ``` The primary function for writing to a buffer is `cxBufferWrite()` @@ -163,10 +184,6 @@ If the write operation triggered a [flush](#flushing), however, the position will be shifted left alongside the shifted buffer contents. In case the data at which the current position points gets flushed, the new position will be zero. -If you already (roughly) know how many bytes you will be writing to a buffer, -you can save some allocations during auto-extension when you invoke `cxBufferMinimumCapacity()` before writing the data. -Usually you do not need to do this, unless you have many subsequence writes which impose the risk of multiple unnecessary reallocations. - ## Read ```C