Add wrbuf_cstr_null
[yaz-moved-to-github.git] / src / wrbuf.c
index 972acff..e57aab7 100644 (file)
@@ -16,6 +16,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <stdarg.h>
+#include <assert.h>
 
 #include <yaz/wrbuf.h>
 #include <yaz/snprintf.h>
@@ -69,7 +70,7 @@ void wrbuf_write(WRBUF b, const char *buf, size_t size)
     if (size <= 0)
         return;
     if (b->pos + size >= b->size)
-        wrbuf_grow(b, size);
+        wrbuf_grow(b, size + 1);
     memcpy(b->buf + b->pos, buf, size);
     b->pos += size;
 }
@@ -79,7 +80,7 @@ void wrbuf_insert(WRBUF b, size_t pos, const char *buf, size_t size)
     if (size <= 0 || pos > b->pos)
         return;
     if (b->pos + size >= b->size)
-        wrbuf_grow(b, size);
+        wrbuf_grow(b, size + 1);
     memmove(b->buf + pos + size, b->buf + pos, b->pos - pos);
     memcpy(b->buf + pos, buf, size);
     b->pos += size;
@@ -262,8 +263,19 @@ void wrbuf_iconv_reset(WRBUF b, yaz_iconv_t cd)
 
 const char *wrbuf_cstr(WRBUF b)
 {
-    wrbuf_putc(b, '\0');   /* add '\0' */
-    (b->pos)--;           /* don't include '\0' in count */
+    if (b->pos == 0)
+       return "";
+    assert(b->pos < b->size);
+    b->buf[b->pos] = '\0';
+    return b->buf;
+}
+
+const char *wrbuf_cstr_null(WRBUF b)
+{
+    if (!b || b->pos == 0)
+        return 0;
+    assert(b->pos < b->size);
+    b->buf[b->pos] = '\0';
     return b->buf;
 }