Add json_sprintf and json_vsprintf

Fixes #392
This commit is contained in:
Petri Lehtinen
2018-02-08 20:52:10 +02:00
parent 3e81f78366
commit efe6c7b3f2
8 changed files with 78 additions and 1 deletions

View File

@@ -3,6 +3,8 @@ EXPORTS
json_true
json_false
json_null
json_sprintf
json_vsprintf
json_string
json_stringn
json_string_nocheck

View File

@@ -289,6 +289,11 @@ int json_unpack(json_t *root, const char *fmt, ...);
int json_unpack_ex(json_t *root, json_error_t *error, size_t flags, const char *fmt, ...);
int json_vunpack_ex(json_t *root, json_error_t *error, size_t flags, const char *fmt, va_list ap);
/* sprintf */
json_t *json_sprintf(const char *fmt, ...);
json_t *json_vsprintf(const char *fmt, va_list ap);
/* equality */

View File

@@ -787,6 +787,40 @@ static json_t *json_string_copy(const json_t *string)
return json_stringn_nocheck(s->value, s->length);
}
json_t *json_vsprintf(const char *fmt, va_list ap) {
int length;
char *buf;
va_list aq;
va_copy(aq, ap);
length = vsnprintf(NULL, 0, fmt, ap);
if (length == 0)
return json_string("");
buf = jsonp_malloc(length + 1);
if (!buf)
return NULL;
vsnprintf(buf, length + 1, fmt, aq);
if (!utf8_check_string(buf, length)) {
jsonp_free(buf);
return NULL;
}
return jsonp_stringn_nocheck_own(buf, length);
}
json_t *json_sprintf(const char *fmt, ...) {
json_t *result;
va_list ap;
va_start(ap, fmt);
result = json_vsprintf(fmt, ap);
va_end(ap);
return result;
}
/*** integer ***/