From c4d1648ca6c3ac005b75c3b3b0bb79e664bead75 Mon Sep 17 00:00:00 2001 From: Jo-Philipp Wich Date: Tue, 4 May 2021 11:41:17 +0200 Subject: lib: add support for pretty printing JSON to printf() and sprintf() Honour precision specifiers when parsing `J` format strings to enable or disable JSON pretty printing. Signed-off-by: Jo-Philipp Wich --- lib.c | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) (limited to 'lib.c') diff --git a/lib.c b/lib.c index d6889c6..93798b8 100644 --- a/lib.c +++ b/lib.c @@ -1210,6 +1210,7 @@ uc_printf_common(uc_vm *vm, size_t nargs, uc_stringbuf_t *buf) const char *fstr, *last, *p; uc_type_t t = UC_NULL; size_t argidx = 1; + int i, pad_size; if (ucv_type(fmt) == UC_STRING) fstr = ucv_string_get(fmt); @@ -1339,10 +1340,25 @@ uc_printf_common(uc_vm *vm, size_t nargs, uc_stringbuf_t *buf) case 'J': t = UC_STRING; - if (argidx < nargs) - arg.s = ucv_to_jsonstring(vm, uc_get_arg(argidx++)); - else + pad_size = 0; + + for (i = 0; sfmt + i < fp; i++) { + if (sfmt[i] == '.') { + pad_size = 1 + atoi(&sfmt[i + 1]); + fp = &sfmt[i]; + break; + } + } + + if (argidx < nargs) { + arg.s = ucv_to_jsonstring_formatted(vm, + uc_get_arg(argidx++), + pad_size > 0 ? (pad_size > 1 ? ' ' : '\t') : '\0', + pad_size > 0 ? (pad_size > 1 ? pad_size - 1 : 1) : 0); + } + else { arg.s = NULL; + } arg.s = arg.s ? arg.s : xstrdup("null"); -- cgit v1.2.3