Skip to content

Commit 7ad067a

Browse files
committed
Add JSONAppendStringf
1 parent e0fb967 commit 7ad067a

File tree

2 files changed

+23
-8
lines changed

2 files changed

+23
-8
lines changed

include/common/json_utils.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,11 @@ void mg_json_emit_str(struct mbuf *b, const struct mg_str s, int quote);
5353

5454
namespace mgos {
5555

56-
std::string JSONPrintfString(const char *fmt, ...);
56+
// Renders JSON and returns a string.
57+
std::string JSONPrintStringf(const char *fmt, ...);
58+
59+
// Appends JSON to and existing string.
60+
int JSONAppendStringf(std::string *out, const char *fmt, ...);
5761

5862
} // namespace mgos
5963
#endif

src/mgos_json_utils.cpp

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,33 @@
1919

2020
namespace mgos {
2121

22-
int JSONPrinterString(struct json_out *out, const char *buf, size_t len) {
22+
static int JSONStringPrinter(struct json_out *out, const char *buf,
23+
size_t len) {
2324
std::string *res = static_cast<std::string *>(out->u.data);
2425
res->append(buf, len);
2526
return len;
2627
}
2728

28-
std::string JSONPrintfString(const char *fmt, ...) {
29+
int JSONAppendStringf(std::string *out, const char *fmt, ...) {
30+
struct json_out json_out = {};
31+
va_list ap;
32+
va_start(ap, fmt);
33+
json_out.printer = JSONStringPrinter;
34+
json_out.u.data = reinterpret_cast<char *>(out);
35+
int res = json_vprintf(&json_out, fmt, ap);
36+
va_end(ap);
37+
return res;
38+
}
39+
40+
std::string JSONPrintStringf(const char *fmt, ...) {
2941
std::string res;
30-
struct json_out out = {};
42+
struct json_out json_out = {};
3143
va_list ap;
3244
va_start(ap, fmt);
33-
out.printer = JSONPrinterString;
34-
out.u.data = reinterpret_cast<char *>(&res);
35-
json_vprintf(&out, fmt, ap);
45+
json_out.printer = JSONStringPrinter;
46+
json_out.u.data = reinterpret_cast<char *>(&res);
47+
json_vprintf(&json_out, fmt, ap);
3648
va_end(ap);
37-
res.shrink_to_fit();
3849
return res;
3950
}
4051

0 commit comments

Comments
 (0)