From a3e509034b4eada3903fc8e5cdcdf253c207b4b8 Mon Sep 17 00:00:00 2001 From: Stephen Dolan Date: Mon, 10 Sep 2012 16:01:56 +0100 Subject: [PATCH] jv_string_fmt (create printf-formatted JSON strings) --- c/Makefile | 2 +- c/jv.c | 24 ++++++++++++++++++++++-- c/jv.h | 1 + c/jv_test.c | 9 +++++++++ 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/c/Makefile b/c/Makefile index cad2330..c80642d 100644 --- a/c/Makefile +++ b/c/Makefile @@ -27,7 +27,7 @@ parsertest: parser.tab.c lexer.yy.c main.c opcode.c bytecode.c compile.c execute jq: parser.tab.c lexer.yy.c main.c opcode.c bytecode.c compile.c execute.c builtin.c jv.c jv_parse.c jv_print.c jv_dtoa.c jv_unicode.c $(CC) -DJQ_DEBUG=0 -o $@ $^ -jv_test: jv_test.c jv.c jv_print.c jv_dtoa.c +jv_test: jv_test.c jv.c jv_print.c jv_dtoa.c jv_unicode.c $(CC) -DNO_JANSSON -o $@ $^ jv_parse: jv_parse.c jv.c jv_print.c jv_dtoa.c diff --git a/c/jv.c b/c/jv.c index 53e2ef7..73805a0 100644 --- a/c/jv.c +++ b/c/jv.c @@ -4,6 +4,7 @@ #include #include #include +#include #include "jv.h" @@ -81,8 +82,8 @@ jv jv_invalid() { return jv_invalid_with_msg(jv_null()); } -jv jv_invalid_get_message(jv inv) { - jv x = ((jvp_invalid*)inv.val.complex.ptr)->errmsg; +jv jv_invalid_get_msg(jv inv) { + jv x = jv_copy(((jvp_invalid*)inv.val.complex.ptr)->errmsg); jv_free(inv); return x; } @@ -472,6 +473,25 @@ const char* jv_string_value(jv j) { return jvp_string_ptr(&j.val.complex)->data; } +jv jv_string_fmt(const char* fmt, ...) { + int size = 1024; + while (1) { + char* buf = malloc(size); + va_list args; + va_start(args, fmt); + int n = vsnprintf(buf, size, fmt, args); + va_end(args); + if (n < size) { + jv ret = jv_string_sized(buf, n); + free(buf); + return ret; + } else { + free(buf); + size = n * 2; + } + } +} + /* * Objects (internal helpers) */ diff --git a/c/jv.h b/c/jv.h index a3a5e79..c415ee2 100644 --- a/c/jv.h +++ b/c/jv.h @@ -75,6 +75,7 @@ jv jv_string_sized(const char*, int); int jv_string_length(jv); uint32_t jv_string_hash(jv); const char* jv_string_value(jv); +jv jv_string_fmt(const char*, ...); jv jv_object(); jv jv_object_get(jv object, jv key); diff --git a/c/jv_test.c b/c/jv_test.c index 2b5a627..725e5ab 100644 --- a/c/jv_test.c +++ b/c/jv_test.c @@ -108,6 +108,15 @@ int main(){ jv_free(a1); jv_free(a2); jv_free(b); + + assert(jv_equal(jv_string("hello42!"), jv_string_fmt("hello%d%s", 42, "!"))); + char big[20000]; + for (int i=0; i