]> diplodocus.org Git - nmh/commitdiff
Reworked charstring_buffer_copy() to not use strdup() so that
authorDavid Levine <levinedl@acm.org>
Sat, 25 Oct 2014 03:22:47 +0000 (22:22 -0500)
committerDavid Levine <levinedl@acm.org>
Sat, 25 Oct 2014 03:22:47 +0000 (22:22 -0500)
charstrings with null bytes can be supported.  Added
charstring_append_cstring().

h/mh.h
sbr/charstring.c

diff --git a/h/mh.h b/h/mh.h
index 157f3c0..b8c60ca 100644 (file)
--- a/h/mh.h
+++ b/h/mh.h
@@ -60,6 +60,7 @@ void charstring_push_back (charstring_t, const char);
 /* Append possibly multi-byte character(s): */
 void charstring_push_back_chars (charstring_t, const char [], size_t, size_t);
 void charstring_append (charstring_t, const charstring_t);
+void charstring_append_cstring (charstring_t, const char []);
 void charstring_clear (charstring_t);
 /* Don't store return value of charstring_buffer() and use later after
    intervening push_back's; use charstring_buffer_copy() instead. */
index d007e7b..d94961a 100644 (file)
@@ -102,13 +102,25 @@ charstring_append (charstring_t dest, const charstring_t src) {
     const size_t num = src->cur - src->buffer;
 
     if (num > 0) {
-        charstring_reserve (dest, num + (dest->cur - dest->buffer));
+        charstring_reserve (dest, dest->cur - dest->buffer + num);
         memcpy (dest->cur, src->buffer, num);
         dest->cur += num;
         dest->chars += src->chars;
     }
 }
 
+void
+charstring_append_cstring (charstring_t dest, const char src[]) {
+    const size_t num = strlen (src);
+
+    if (num > 0) {
+        charstring_reserve (dest, dest->cur - dest->buffer + num);
+        memcpy (dest->cur, src, num);  /* Exclude src's trailing newline. */
+        dest->cur += num;
+        dest->chars += num;
+    }
+}
+
 void
 charstring_clear (charstring_t s) {
     s->cur = s->buffer;
@@ -134,14 +146,12 @@ charstring_buffer (const charstring_t s) {
 
 char *
 charstring_buffer_copy (const charstring_t s) {
-    char *copy = strdup (charstring_buffer (s));
+    char *copy = mh_xmalloc (s->cur - s->buffer + 1);
 
-    if (copy) {
-        return copy;
-    } else {
-        advise ("strdup", "unable to copy charstring buffer");
-        return NULL;
-    }
+    /* Use charstring_buffer() to null terminate the buffer. */
+    memcpy (copy, charstring_buffer (s), s->cur - s->buffer + 1);
+
+    return copy;
 }
 
 size_t