Wed, 02 Apr 2025 20:25:50 +0200
document buffer write functions
relates to #451
docs/Writerside/topics/buffer.h.md | file | annotate | diff | comparison | revisions |
--- a/docs/Writerside/topics/buffer.h.md Tue Apr 01 19:21:04 2025 +0200 +++ b/docs/Writerside/topics/buffer.h.md Wed Apr 02 20:25:50 2025 +0200 @@ -83,21 +83,47 @@ size_t cxBufferWrite(const void *ptr, size_t size, size_t nitems, CxBuffer *buffer); -size_t cxBufferAppend(const void *ptr, size_t size, size_t nitems, - CxBuffer *buffer); - int cxBufferPut(CxBuffer *buffer, int c); size_t cxBufferPutString(CxBuffer *buffer, const char *str); int cxBufferTerminate(CxBuffer *buffer); +size_t cxBufferAppend(const void *ptr, size_t size, size_t nitems, + CxBuffer *buffer); + int cxBufferMinimumCapacity(CxBuffer *buffer, size_t capacity); ``` -<warning> -TODO: document -</warning> +The primary function for writing to a buffer is `cxBufferWrite()` +which writes up to `nitems` with `size` bytes each from the memory pointed to by `ptr` to the buffer. + +When the capacity of the buffer is not sufficient and the `CX_BUFFER_AUTO_EXTEND` is not set in the buffer, +items that do not fit into the buffer are discarded. +The function always returns the actual number of items successfully written. +This equals the number of bytes if and only if `size=1`. + +The function `cxBufferPut()` is a `putc()`-like wrapper for `cxBufferWrite()` which writes the character `c`, +converted to an `unsigned char` to the buffer. +Just like `putc()` this function returns the written character on success, and `EOF` on failure, +but it does _not_ set `errno` on failure. + +The function `cxBufferPutString()` is a convenience function, +that uses stdlib `strlen()` to compute the length of `str` and then invokes `cxBufferWrite()`. + +All of the above functions advance the buffers position by the number of bytes written, +and cause the _size_ of the buffer to grow, if necessary, to contain all written bytes. +On the other hand, `cxBufferTerminate()` writes a zero-byte at the current position, +effectively creating a zero-terminated string whose size equals the buffer size. + +The function `cxBufferAppend()` writes the data to end of the buffer (given by its size) regardless of the current position, +and it also does _not_ advance the position. +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