Files
libucore/include/ucore_buffer.h
T
Nils O. Selåsdal 4dca24953f readd include dir
2012-11-15 17:30:40 +01:00

84 lines
1.8 KiB
C

#ifndef UCORE_BUFFER_H_
#define UCORE_BUFFER_H_
#include <stddef.h>
#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;
};
/** Allocatea 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,void *data,size_t len);
/** 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
*/
size_t uc_gbuf_remaining(const GBuf *buf)
{
return buf->len - buf->used;
}
#ifdef __cplusplus
}
#endif
#endif