1
0

util: json: Use virBuffer in JSON->string conversion

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>
This commit is contained in:
Peter Krempa 2019-03-26 14:56:22 +01:00
parent 29ad523018
commit 6a604f759d

View File

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