--- cfg_buf.c 2004/11/20 11:34:52 1.11
+++ cfg_buf.c 2004/11/28 12:58:25 1.12
@@ -37,12 +37,15 @@
#include "cfg_buf.h"
#include "cfg_fmt.h"
+/* opaque buffer data structure */
struct cfg_buf_st {
- char *buf_ptr;
- size_t buf_size;
- size_t buf_len;
+ char *buf_ptr; /* pointer to buffer start */
+ size_t buf_size; /* total size of buffer in bytes */
+ size_t buf_len; /* character length of string in buffer */
+ /* (not counting NUL-termination) */
};
+/* create a new buffer object */
cfg_rc_t cfg_buf_create(cfg_buf_t **buf)
{
if (buf == NULL)
@@ -55,6 +58,7 @@
return CFG_OK;
}
+/* resize (destroy, expand or shrink) the buffer */
cfg_rc_t cfg_buf_resize(cfg_buf_t *buf, signed int n)
{
char *cp;
@@ -62,7 +66,7 @@
if (buf == NULL)
return CFG_ERR_ARG;
if (n == 0) {
- /* destroy buffer */
+ /* special case: destroy buffer */
if (buf->buf_ptr != NULL)
free(buf->buf_ptr);
buf->buf_ptr = NULL;
@@ -76,6 +80,7 @@
return CFG_ERR_SYS;
buf->buf_size = n+1;
buf->buf_len = 0;
+ *buf->buf_ptr = '\0';
}
else {
if ((cp = realloc(buf->buf_ptr, buf->buf_size+n)) == NULL)
@@ -91,6 +96,36 @@
return CFG_OK;
}
+/* append a string to the buffer */
+cfg_rc_t cfg_buf_append(cfg_buf_t *buf, const char *str, size_t len)
+{
+ cfg_rc_t rc;
+
+ if (buf == NULL || str == NULL || len == 0)
+ return CFG_ERR_ARG;
+ if ((rc = cfg_buf_resize(buf, len)) != CFG_OK)
+ return rc;
+ memcpy(buf->buf_ptr + buf->buf_len, str, len);
+ buf->buf_len += len;
+ *(buf->buf_ptr + buf->buf_len) = '\0';
+ return CFG_OK;
+}
+
+/* remove a trailing string from the buffer */
+cfg_rc_t cfg_buf_remove(cfg_buf_t *buf, const char *str, size_t len)
+{
+ if (buf == NULL || len == 0)
+ return CFG_ERR_ARG;
+ if (len > buf->buf_len)
+ return CFG_ERR_USE;
+ if (str != NULL)
+ memcpy((void *)str, buf->buf_ptr + buf->buf_len - len, len + 1);
+ buf->buf_len -= len;
+ *(buf->buf_ptr + buf->buf_len) = '\0';
+ return CFG_OK;
+}
+
+/* append a formatted string to the buffer */
cfg_rc_t cfg_buf_format(cfg_buf_t *buf, const char *fmt, ...)
{
va_list ap;
@@ -102,6 +137,7 @@
return rc;
}
+/* append a formatted string to the buffer (va_list based) */
cfg_rc_t cfg_buf_vformat(cfg_buf_t *buf, const char *fmt, va_list ap)
{
cfg_rc_t rc;
@@ -113,7 +149,7 @@
return CFG_ERR_FMT;
if ((rc = cfg_buf_resize(buf, n)) != CFG_OK)
return rc;
- if ((n = cfg_fmt_vsprintf(buf->buf_ptr + buf->buf_len,
+ if ((n = cfg_fmt_vsprintf(buf->buf_ptr + buf->buf_len,
buf->buf_size - buf->buf_len,
fmt, ap)) == -1)
return CFG_ERR_FMT;
@@ -121,6 +157,7 @@
return CFG_OK;
}
+/* return the buffer string */
cfg_rc_t cfg_buf_content(cfg_buf_t *buf, char **ptr, size_t *len, size_t *size)
{
if (buf == NULL)
@@ -139,6 +176,7 @@
return CFG_OK;
}
+/* destroy buffer object */
cfg_rc_t cfg_buf_destroy(cfg_buf_t *buf)
{
if (buf == NULL)
|