This is an automated email from the ASF dual-hosted git repository. swebb2066 pushed a commit to branch escape_control_chars in repository https://gitbox.apache.org/repos/asf/logging-log4cxx.git
commit 72897f71fcf717b6c5d2d961457401325e304c68 Author: Stephen Webb <[email protected]> AuthorDate: Mon Jul 21 13:22:09 2025 +1000 Escape control characters in JSONLayout data --- src/main/cpp/jsonlayout.cpp | 48 ++++++++++++++++------------------------- src/test/cpp/jsonlayouttest.cpp | 7 ++++++ 2 files changed, 26 insertions(+), 29 deletions(-) diff --git a/src/main/cpp/jsonlayout.cpp b/src/main/cpp/jsonlayout.cpp index d8d062d7..e8668610 100644 --- a/src/main/cpp/jsonlayout.cpp +++ b/src/main/cpp/jsonlayout.cpp @@ -218,29 +218,24 @@ void JSONLayout::appendItem(const LogString& input, LogString& buf) /* add leading quote */ buf.push_back(0x22); - logchar specialChars[] = - { - 0x08, /* \b backspace */ - 0x09, /* \t tab */ - 0x0a, /* \n newline */ - 0x0c, /* \f form feed */ - 0x0d, /* \r carriage return */ - 0x22, /* \" double quote */ - 0x5c, /* \\ backslash */ - 0x00 /* terminating NULL for C-strings */ - }; - size_t start = 0; - size_t found = input.find_first_of(specialChars, start); + size_t index = 0; - while (found != LogString::npos) + for (int ch : input) { - if (found > start) + if (0x22 == ch || 0x5c == ch) + ; + else if (0x20 <= ch) + { + ++index; + continue; + } + if (index > start) { - buf.append(input, start, found - start); + buf.append(input, start, index - start); } - switch (input[found]) + switch (input[index]) { case 0x08: /* \b backspace */ @@ -285,20 +280,15 @@ void JSONLayout::appendItem(const LogString& input, LogString& buf) break; default: - buf.push_back(input[found]); + buf.push_back(0x5c); + buf.push_back(0x75); // 'u' + buf.push_back(((ch & 0xF000) >> 12) + 0x30); + buf.push_back(((ch & 0xF00) >> 8) + 0x30); + buf.push_back(((ch & 0xF0) >> 4) + 0x30); + buf.push_back((ch & 0xF) + 0x30); break; } - - start = found + 1; - - if (found < input.size()) - { - found = input.find_first_of(specialChars, start); - } - else - { - found = LogString::npos; - } + start = ++index; } if (start < input.size()) diff --git a/src/test/cpp/jsonlayouttest.cpp b/src/test/cpp/jsonlayouttest.cpp index fda39fca..0caacdbc 100644 --- a/src/test/cpp/jsonlayouttest.cpp +++ b/src/test/cpp/jsonlayouttest.cpp @@ -163,6 +163,13 @@ public: appendQuotedEscapedString(cr_escaped, cr); LOGUNIT_ASSERT_EQUAL(cr_expected, cr_escaped); + + logchar esc[] = {0x1e, 0x00}; + logchar esc_expected[] = {0x22, 0x5c, 'u', 0x30, 0x30, 0x31, 0x3e, 0x22, 0x00}; /* ESC */ + LogString esc_escaped; + + appendQuotedEscapedString(esc_escaped, esc); + LOGUNIT_ASSERT_EQUAL(esc_expected, esc_escaped); } /**
