From 0ac39e0e5da0d73936d5b846a18315f83139064e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Barnab=C3=A1s=20P=C5=91cze?= Date: Wed, 1 Jul 2026 15:16:03 +0200 Subject: [PATCH] spa: utils: json: add `spa_json_encode_stringn()` Add the function `spa_json_encode_stringn()` that works very similarly to `spa_json_encode_string()`, with the difference that it works with non-null terminated strings (e.g. `std::string_view`). `spa_json_encode_string()` is then implemented with this new function. Additionally, since the input string is no longer null terminated, escape bytes of value 0. This is probably better that putting it into the result. --- spa/include/spa/utils/json-core.h | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/spa/include/spa/utils/json-core.h b/spa/include/spa/utils/json-core.h index 9745000cf..49e6eb0b1 100644 --- a/spa/include/spa/utils/json-core.h +++ b/spa/include/spa/utils/json-core.h @@ -665,14 +665,18 @@ SPA_API_JSON int spa_json_parse_string(const char *val, int len, char *result) return spa_json_parse_stringn(val, len, result, len+1); } -SPA_API_JSON int spa_json_encode_string(char *str, int size, const char *val) +SPA_API_JSON size_t spa_json_encode_stringn(char *dst, size_t capacity, const char *src, size_t length) { - int len = 0; static const char hex[] = { "0123456789abcdef" }; -#define __PUT(c) { if (len < size) *str++ = c; len++; } + + size_t len = 0; +#define __PUT(c) do { if (len < capacity) *dst++ = c; len++; } while (0) + __PUT('"'); - while (*val) { - switch (*val) { + for (; length > 0; length--, src++) { + const char val = *src; + + switch (val) { case '\n': __PUT('\\'); __PUT('n'); break; @@ -690,19 +694,18 @@ SPA_API_JSON int spa_json_encode_string(char *str, int size, const char *val) break; case '\\': case '"': - __PUT('\\'); __PUT(*val); + __PUT('\\'); __PUT(val); break; default: - if (*val > 0 && *val < 0x20) { + if ((unsigned char) val < 0x20) { __PUT('\\'); __PUT('u'); __PUT('0'); __PUT('0'); - __PUT(hex[((*val)>>4)&0xf]); __PUT(hex[(*val)&0xf]); + __PUT(hex[(val>>4)&0xf]); __PUT(hex[val&0xf]); } else { - __PUT(*val); + __PUT(val); } break; } - val++; } __PUT('"'); __PUT('\0'); @@ -710,6 +713,11 @@ SPA_API_JSON int spa_json_encode_string(char *str, int size, const char *val) return len-1; } +SPA_API_JSON int spa_json_encode_string(char *dst, int capacity, const char *src) +{ + return spa_json_encode_stringn(dst, capacity, src, strlen(src)); +} + /** * \} */