fix: escape control characters and count JSON string lengths correctly

calcEscapedLength looped from strlen(raw) down to 1, counting the
terminator instead of the first character.  A value starting with a
character that needs escaping was counted one byte short, so the fit
check could let it be written one byte past the buffer.  Control
characters other than \b\f\n\r\t were copied raw, which isn't valid
JSON.

Both now go through one escapeChar helper, which also escapes the
remaining control characters as \u00XX.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
cjkas 2026-10-11 13:30:42 +02:00
parent 48676b05c3
commit b2294ced34
2 changed files with 31 additions and 51 deletions

View file

@ -16,6 +16,9 @@ class JsonFormatter {
virtual void _safecat(const char *val, bool escape = false);
void _appendNumber(const char *name);
public:
// Writes c as it must appear inside a JSON string (out needs 7 bytes) and
// returns its length.
static size_t escapeChar(char c, char *out);
void escapeString(const char *raw, char *escaped);
uint32_t calcEscapedLength(const char *raw);
void beginObject(const char *name = nullptr);