#ifndef UC_BUFFER_H_ #define UC_BUFFER_H_ #include #ifdef __cplusplus extern "C" { #endif /** A GBuf is a growing reference counted buffer. * The buffer is dynamically allocated, and can grow * as you append data to it. Reference counting takes care * of automatically freeing the GBuf and its buffer when it * reaches 0 */ typedef struct GBuf GBuf; struct GBuf { /** Allocated buffer length.*/ size_t len; /** Used space in the buffer */ size_t used; /** Reference count */ size_t ref_cnt; /** The data */ void *buf; }; /** Allocate a new GBuf. * * @param initsz Intial capacity of the GBuf * @return New GBuf, or NULL if allocation fails, * The returned GBuf will have ref_cnt=1 */ GBuf* uc_new_gbuf(size_t initsz); /** Increment the reference count of the GBuf. * * @param buf Bufffer */ void uc_gbuf_ref(GBuf *buf); /** Decrement the reference count of the GBuf, free it if ref_cnt reaches 0 * * @param buf Bufffer */ void uc_gbuf_unref(GBuf *buf); /** Append data to the GBuf. * Data is coped into the buffer, starting at &buf->data[used] * The GBuf automatically grows if needed. * * @param buf buffer to append to * @param data data to copy to the GBuf * @param len length of @data to copy * @return 0 on success, -1 on failure when allocation fails if he buffer * needs to grow */ int uc_gbuf_append(GBuf *buf,const void *data,size_t len); /** Do printf formatting on a GBuf. * The buffer will grow as needed, * The buffer ensures that the added string will be nul terminated, * however the nul terminator is not counted in the ->used member. * * @param buf The GBuf * @param fmt printf stype formatting string * @param ... format arguments * * @return The number of chars written excluding the terminating nul * character , or negative if an error occurs */ int uc_gbuf_printf(GBuf *buf, const char *fmt, ...) __attribute__((format(printf, 2, 3))); /** Expand the capacity of the GBuf. * * @param buf buffer to grow * @return 0 on success, -1 on failure when allocation fails */ int uc_gbuf_grow(GBuf *buf, size_t addlen); /** Remaining unised space of the GBuf. * @param buff buffer * @return length of unused space */ static inline size_t uc_gbuf_remaining(const GBuf *buf) { return buf->len - buf->used; } #ifdef __cplusplus } #endif #endif