]> git.ipfire.org Git - thirdparty/libvirt.git/commitdiff
util: json: Use virBuffer in JSON->string conversion
authorPeter Krempa <pkrempa@redhat.com>
Tue, 26 Mar 2019 13:56:22 +0000 (14:56 +0100)
committerPeter Krempa <pkrempa@redhat.com>
Wed, 3 Apr 2019 09:58:10 +0000 (11:58 +0200)
The last step of the conversion involves copying of the generated JSON
into a separate string. We can use a virBuffer to do this as this will
also allow to subsequently use the buffer when we actually need to do
some other formatting of the string.

Signed-off-by: Peter Krempa <pkrempa@redhat.com>
Reviewed-by: Laine Stump <laine@laine.org>
src/util/virjson.c

index d5d66f879f6e1552ce62a79ad6553ee1bab9bff6..7dfc5899447cac3656e6307597869b607fc1b7a3 100644 (file)
@@ -28,6 +28,7 @@
 #include "virlog.h"
 #include "virstring.h"
 #include "virutil.h"
+#include "virbuffer.h"
 
 #if WITH_YAJL
 # include <yajl/yajl_gen.h>
@@ -1969,17 +1970,18 @@ virJSONValueToStringOne(virJSONValuePtr object,
 }
 
 
-char *
-virJSONValueToString(virJSONValuePtr object,
+static int
+virJSONValueToBuffer(virJSONValuePtr object,
+                     virBufferPtr buf,
                      bool pretty)
 {
     yajl_gen g;
     const unsigned char *str;
-    char *ret = NULL;
     yajl_size_t len;
 # ifndef WITH_YAJL2
     yajl_gen_config conf = { pretty ? 1 : 0, pretty ? "  " : " "};
 # endif
+    int ret = -1;
 
     VIR_DEBUG("object=%p", object);
 
@@ -2009,13 +2011,12 @@ virJSONValueToString(virJSONValuePtr object,
         goto cleanup;
     }
 
-    ignore_value(VIR_STRDUP(ret, (const char *)str));
+    virBufferAdd(buf, (const char *) str, len);
+    ret = 0;
 
  cleanup:
     yajl_gen_free(g);
 
-    VIR_DEBUG("result=%s", NULLSTR(ret));
-
     return ret;
 }
 
@@ -2030,17 +2031,36 @@ virJSONValueFromString(const char *jsonstring ATTRIBUTE_UNUSED)
 }
 
 
-char *
-virJSONValueToString(virJSONValuePtr object ATTRIBUTE_UNUSED,
+static int
+virJSONValueToBuffer(virJSONValuePtr object ATTRIBUTE_UNUSED,
+                     virBufferPtr buf ATTRIBUTE_UNUSED,
                      bool pretty ATTRIBUTE_UNUSED)
 {
     virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("No JSON parser implementation is available"));
-    return NULL;
+    return -1;
 }
 #endif
 
 
+char *
+virJSONValueToString(virJSONValuePtr object,
+                     bool pretty)
+{
+    VIR_AUTOCLEAN(virBuffer) buf = VIR_BUFFER_INITIALIZER;
+    char *ret = NULL;
+
+    if (virJSONValueToBuffer(object, &buf, pretty) < 0)
+        return NULL;
+
+    ret = virBufferContentAndReset(&buf);
+
+    VIR_DEBUG("result=%s", NULLSTR(ret));
+
+    return ret;
+}
+
+
 /**
  * virJSONStringReformat:
  * @jsonstr: string to reformat